Interesting problem

I was just practicing writing silly little programs to practice what little bit I know at this point, and have run into an interesting problem.

When I run this program, if I input something like ssssssss, it repeats the first cout as many times as I enter letters.

Why is this happening and how can I fix it?

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <fstream>

int main()
{
	char choice;
do {
	std::cout << "Which letter would you like to write to file? (a, b, c, d) ";
	
	std::cin >> choice;
	
	if (choice !='a' && choice !='b' && choice !='c' && choice !='d')
	std:: cout << "Please enter a valid choice" << '\n';

}

	while (choice !='a' && choice !='b' && choice !='c' && choice !='d');

	std::ofstream myfile;
	myfile.open ("example.txt");
	myfile << choice << '\n';
	myfile.close();

	switch (choice)
	{ 
	case 'a':
	std::cout << "You chose a. Please check example.txt" << '\n';
	break;

	case 'b':
	std::cout << "You chose b. Please check example.txt" << '\n';
	break;


	case 'c':
	std::cout << "You chose c. Please check example.txt" << '\n';
	break;

	case 'd':	
	std::cout << "You chose d. Please check example.txt" << '\n';
	break;

	default:
	std::cout << "You did not enter a valid choice" << '\n';

}

return 0;

}
Last edited on
To put it simply, its expecting a single char, so when you enter multiple chars in, it prints out the cout statements resulting from each of them.

To stop this from happening, you need to add a cin.clear() and cin.ignore statements within your if-statement, before the cout message.

so:
1
2
3
4
5
6
	if (choice !='a' && choice !='b' && choice !='c' && choice !='d')
	{
	   std::cin.clear(); // clears error flag for buffer so it can be used again
	   std::cin.ignore(1000, '\n'); //ignores up to 1000 characters
	   std:: cout << "Please enter a valid choice" << '\n';
	}
Oh! Okay. Thank you :-)
After looking at this again, I realize how unnecessary switch was when I could have simply wrote

std::cout << "You chose " << choice << ". Please check example.txt" << '\n';

Oh well, just practicing what I have learned so far.
Topic archived. No new replies allowed.