There's a problem with the flow of control in my program

Oct 29, 2014 at 9:29pm
....
Last edited on Nov 2, 2014 at 7:09am
Oct 29, 2014 at 9:47pm
The program would not compile for me as is. Made a change compiled and it worked fine.

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
int main()
{
	char choice[25];
	char choice2 ='D';

	do
	{
		if (toupper(choice2) == 'D')
		{
			std::cout << "Enter a string: ";
			std::cin.getline(choice, 25);
			std::cout << choice << "\n";
		}

		std::cout << "\t";
		std::cout << "A) Count the vowels in the string" << "\n";
		std::cout << "\t";
		std::cout << "B) Count the consonants in the string" << "\n";
		std::cout << "\t";
		std::cout << "C) Count both vowels and consonants" << "\n";
		std::cout << "\t";
		std::cout << "D) Enter another string" << "\n";
		std::cout << "\t";
		std::cout << "E) Exit this program" << "\n";
		std::cout << "\n";
		std::cout << "Enter A, B, C, D, or E." << "\n";
		std::cin >> choice2;

		if (toupper(choice2) != 'E' || toupper(choice2) != 'D')
			testString(choice, choice2);

	} while (toupper(choice2) != 'E');

	return 0;
}
Oct 29, 2014 at 10:01pm
When you do std::cin.getline(choice,25) at line 13 it will read up to 25 characters and store them in choice. If you enter 10 characters, it will store those 10 and a terminating null byte, but the remaining 14 characters contain whatever undefined bytes happen to be at that location.

Then at line 64 you are looping through all 25 characters instead of just the 10 that are valid. To fix this, change line 64 to:
for (int n = 0; choice1[n]; n++)
Oct 29, 2014 at 10:32pm
Thank you so much dhayden, if it wasn't for you I would have NEVER figured that out.
Oct 30, 2014 at 4:04am
........
Last edited on Nov 2, 2014 at 7:09am
Oct 30, 2014 at 11:57am
Line 66 getline is where this is failing.

1
2
3
4
5
6
7
if (toupper(choice2) == 'D') // Works
	{
		std::cin.sync();
		std::cout << "Enter a string: ";
		std::cin.getline(choice, 25);
		std::cout << "\"" << choice << "\"" << "\n";
	}
Last edited on Oct 30, 2014 at 11:58am
Topic archived. No new replies allowed.