weird behaviour

i have a just-kidding program :D like this:

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

int reverse() {
	char word;
	int quit = 1;
	word = getch();
	word += 1;
	cout << word;
	cin >> quit;
	if (quit == 0)
		return EXIT_SUCCESS;
	else
		reverse();
}

int main () {
	cout << "word reverser: ";
	reverse();
	getch();
	return 0;
}


for example:

b9

b is the first character i entered (which is 'a') and 9 is the second input of my program that tells the program that i want to continue (recursive the program), but why when i entered:

wasdasdads [then press enter]

where w is the first input (which is 'v') and the rest is random input. and what happen next is the program waits for my input and then when i press any key, for example, asdasdasd, it turns out to be:

btebtebte

and never stops, why is that? bug? or the compiler's bug?
The only thing that springs to mind is that word is a char - only the first character is registered. When you enter vasdasdads, it takes the 'v' as the word character, then takes the remainder as the quit value. However, quit is an integer type, and it's taking a list of characters as an input - not good.

You could treat quit the same as word; set quit type to char, and use getch() to take the value after the first, like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <conio.h>
using namespace std;

int reverse() {
	char quit = '1';			//	Initialize Quit=1
	while (quit != '0'){		//	Until Quit is set = 0
	char word;			
	word = getch();		//	get character from input
	word += 1;			//	Add 1
	cout << word;		//	print the character after input (ASCII)
	quit = getch();		//	Input for quit parameter, 0 to end
	};
	return EXIT_SUCCESS;	//	Return EXIT_SUCCESS variable.
}

int main () {
	cout << "word reverser: ";
	reverse();
	getch();
	return 0;
}



The input:
vasdadsd
becomes an output of
wtbbe
as every other character is being taken as a value of quit.
Last edited on
but how is that possibly happen? i mean, what happen "inside"? is that because overflow or something? it doesn't make sense to me...
Well one problem here is that your using getch and cin together. The input from cin is not guaranteed to come from the keyboard and so the two really don't work together like this. If you want getch, just use it exclusively.

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 <conio.h>
using namespace std;

int reverse() {
	char word;
	// int quit = 1;
	word = getch();
	if( word == '0' )
		return EXIT_SUCCESS; //By the way, why use this int value? Why not just make this a void function?
	word += 1;
	cout << word;
	// cin >> quit;
	// if (quit == 0)
	//	return EXIT_SUCCESS;
	return reverse(); //you forgot to add a return value here as well
}

int main () {
	cout << "word reverser: ";
	reverse();
	// getch();
	return 0;
}
Topic archived. No new replies allowed.