While loop and reversing a string

Hello!

My question is my code is working up until the while loop to do another message. It loops back with the same array again. I tried clearing the array but it just prints out an empty array. Is there a way to clear out the array and have the user input another message to fill the array again and print it again?

Thanks!

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
26
27
28
29
30
31
32
33
34
 void Reverse(char *C, int n) {
	stack<char> S;
	for (int i = 0; i < n; i++) {
		S.push(C[i]);
	}

	for (int i = 0; i < n; i++) {
		C[i] = S.top();
		S.pop();
	}
}

void clearC(char C[]) {
	for (int i = 0; i < 52; i++) {
		C[i] = 0;
	}
}

int main()
{
	char C[52];
	int userInput = 1;
	while (userInput == 1){
	printf("Enter a message: ");
	scanf("%[^\n]s", C);
	Reverse(C, strlen(C));
	printf("Output = %s \n", C);
	cout << "Would you like to try again? (Yes = 1, No = 0):  ";
	cin >> userInput;
	}

	system("PAUSE");
    return 0;
} 
try to declare
char C[52],
after line 24.
That did not work. It still doesn't ask for an input from the user.
Why are you mixing C-stdio functions (scanf(), printf()) with C++ streams, that is just asking for trouble as is using C-strings instead of C++ streams.

Do you realize that the C++ extraction operator leaves a new line character in the buffer which your scanf() will take as it's only input?

Figured it out. I have to add getchar after the cin in order for it to work.

Need a little more explanation on why that is though.
You didn't answer my question about mixing C and C++ input methods. If you're writing a C++ stick with C++ streams, if you're writing a C program stick with C-stdio functions, don't mix the two.

I have to add getchar after the cin in order for it to work.

cin.get() would be a better option for a C++ program and getline() would be a better option for that scanf() call.

Topic archived. No new replies allowed.