Strange output in reverse string program

Have to reverse a line of string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
#include <string.h>
using namespace std;

int main(int argc, char **argv) {

  char *reverse = argv[argc-1];
  char *left = reverse;
  int length = strlen(reverse);
  char *right = reverse+length-1;
  char temp;

  while(right-left>=1){
    temp=*left;
    *left=*right;
    *right=temp;
    ++left;
    --right;
  }
string x;
getline (cin, x);
 cout<< (x, reverse);

}


Input: emperor make jeopardy yield moon job incandescent stay set
Output: noitulos/EjyZN96sYn272xkS8kND-nur/ (what?!)
I guess you borrowed the code without noticing that it is supposed to be run from the command-line. You type the name of the program followed by the word which you want to be reversed.

e.g. your program is named 'reverse', at the command line type
reverse "emperor make jeopardy yield moon job incandescent stay set"

and press enter.

You can list the parameters received by your program like this:
1
2
    for (int i=0; i<argc; i++)
        cout << i << ":  " <<  argv[i] << '\n';
hmmm...what if I don't want to run it from command line, and just run it in the program with an input? Is there a way?
Is there a way?

Of course there's a way.
First get the input as a string.
Then use your code to process the characters in that string instead of the command-line parameter.
I'm not sure how to process the amount of arguments (otherwise, the program wouldn't stop, would it now), this is the best I could do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 #include <iostream>
#include <string.h>
using namespace std;

int main() {
string x;
getline (cin, x);
int argc, char** argv;
x= argc, argv;
  char *reverse = argv[argc-1];
  char *left = reverse;
  int length = strlen(reverse);
  char *right = reverse+length-1;
  char temp;

  while(right-left>=1){
    temp=*left;
    *left=*right;
    *right=temp;
    ++left;
    --right;
  }
  cout<< x;

}
Last edited on
ah, never mind, I forgot about C++'s reverse algorithm. That solved it simply.
Topic archived. No new replies allowed.