views:

132

answers:

4

I am having a problem, but I cannot figure out what I'm doing wrong. I'm not sure if it's a problem with my loop, or the cin buffer is not being cleaned. I am doing a program that transforms a C-style string to uppercase, however if the user enters more than 11 characters, then the function should only display the first 11, and anything after that should not be displayed.the problem is that if I enter more than 11 characters, then my loop never stops and keeps telling the user that the answer entered is invalid and if he would like to enter a new string.

A: 

The issue comes from when you're trying to clear your buffer. When you return from cStringToUpper there are still extra characters in your buffer, but you're immediately looking for y/q.

Bryan
A: 

You give cin.getline a buffer 12 long so it will only take that many characters, the rest are still in the buffer. If you instead use

 string str;
 cin.getline(str)

Then you will get the whole line, then you can crop it at 11 characters. Not 100% on the cin-syntax but you get the idea.

Or move the ignore-part above

cin >>cont;

to ignore the extra characters that way.

dutt
A: 
cin >> cont;
cout << "\n" << endl;
cin.ignore(200,'\n');

should be

cin.ignore(200,'\n');
cin >> cont;
cout << "\n" << endl;
Donotalo
A: 

You may correct your program by modifying your cStringToUpper fn. something like:

...    
int loopCount;
char buffer[256];
cin.getline(buffer,256);
strncpy(letters, buffer, 11);
//letters[11]= '\0';
cout << "\n" << endl;
...
Manish Shukla