printing a string backwards

When I run this code, the same string that I entered is couted, except that I switch the first and last letters, the second-to-last and second letter, etc.

#include <iostream>
#include <string.h>

using namespace std;
const int Arsize = 30;

int main()
{
cout << "Enter a string\n";
char strine[Arsize];
cin.getline(strine, Arsize);
//for (int i = strlen(strine)-1; i>=0; i--)
//strine[i]='k';
for (int i = strlen(strine)-1, j=0; i>=((strlen(strine))/2); i--, j++)
strine[i], strine[j]=strine[j], strine[i];
for (int i = 0; i<=strlen(strine)-1; i++)
cout << strine[i];
return 0;
}
Please use [code] tags -- it makes life so much easier for those who want to help you.

Line 15:

14
15
  for (int i = strlen(strine)-1, j=0; i>=((strlen(strine))/2); i--, j++)
    strine[i], strine[j]=strine[j], strine[i];

You are not changing anything. The comma isn't doing what you think it is. That is, you can only assign one thing at a time, not two, as in Python.

You'll have to have a temporary variable, assign strine[i] to it, copy j to i, then the temp to j.

Hope this helps.
Maybe use the .size() function to figure out how many characters are in the string.

http://www.cplusplus.com/reference/string/string/size/

Then loop through each element of the string printing it from last to first.

It could look something like this

1
2
3
4
5
6
7

std::string str = "Hello World";

for (unsigned int i = str.size() ; i > 0; i--){
   //code to print stuff
}
...except he is using a c-string and not a std::string.
My mistake, just assumed it was C++ because, well the forum heh.

You could make a loop to count the size of the c-string. The logic of the loop above would remain the same.



Maybe something like this (my understanding is a c-string is just a regular c++ string with a null character at the end)

1
2
3
4
5
6
7
8
9
10
int c_str_size = 0;
std::string str "Hello World\0" //or however else you have your c-string set up

for (int i = 0; str[i] != '\0'; i++){
      c_str_size++;
     }

for (int i = c_str_size - 1 ; i > 0; i--){//skip the first null character if you want or print it and remove -1
   //code to print stuff
}



basically just derive the .size() function for your own usage.
Last edited on
You could make a loop to count the size of the c-string.
Other than as an educational exercise, there's no point in reinventing the wheel. The strlen() function is already in the library and fulfils the requirement.
http://www.cplusplus.com/reference/cstring/strlen/
Good info there Chervil :)

I haven't really messed with cstrings all that much. Sometimes I find it overwhelming to look through all the libraries and end up making functions myself lol. It's probably not the best way to go about it xD
Last edited on
Topic archived. No new replies allowed.