I’m having a problem getting my do/while loop to function properly.
This program runs good the first go-around, but when i enter ‘y’ when it asks if i would like to “tell more” the program just asks the user the question (not allowing me to enter a string) and then couts the statements. What am I doing wrong? and how do i get it to function properly?
using namespace std;
int main()
{
int i, numspaces = 0;
char nextChar;
string trimstring;
string uc, rev;
string answer;
char temp;
cout << "\n\n John Acosta"
<<" Exercise 1\n"
<< "\n\n This program will take your string, count the number\n"
<< " of chars and words, UPPERCASE your string, and reverse your string.";
string astring;
do {
cout << "\n\nTell me something about yourself: ";
getline (cin, astring);
trimstring = astring;
uc = astring;
rev = astring;
for (i=0; i<int(astring.length()); i++)
{
nextChar = astring.at(i); // gets a character
if (isspace(astring[i]))
numspaces++;
}
trimstring.erase(remove(trimstring.begin(),trimstring.end(),' '),trimstring.end());
transform(uc.begin(), uc.end(),uc.begin(), ::toupper);
for (i=0; i<rev.length()/2; i++)
{
temp = rev[i];
rev[i] = rev[rev.length()-i-1];
rev[rev.length()-i-1] = temp;
}
cout << "\n\tYou Entered: " << astring
<< "\n\tIt has "<<trimstring.length()
<< " chars and "<<numspaces+1
<< " words."
<< "\n\tUPPERCASE: "<<uc
<< "\n\tReversed: "<<rev
<< "\n\n";
cout<<"\n\nwant to tell me more? Enter \"y\" for YES and \"n\" for NO\n\n";
cin>>answer;
cout<<"\n";
} while(answer == "y"); //contiue loop while answer is 'y'; stop when 'n'
{
cout <<"\n Thanks. Goodbye!\n"; //when loop is done
}
return 0;
}
The input operator
>>works like this: First it skips whitespace, if any; Then it reads the string until it reaches the next whitespace, in your case the newline after the'y'. This newline is then left in the stream so when you at the beginning of the loop dogetlineyou get that newline left after the"y".You can remove this by using the
ignorefunction: