0

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; } 
2
  • For a start, I would put some code in to check if answer == y or Y (I leave it to you to look up how to do that) because if the user's got caps lock on, the do/while loop will fail at the moment. Commented Jan 15, 2013 at 9:15
  • Reduce this to a short self contained correct example. Commented Jan 15, 2013 at 9:15

1 Answer 1

4

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 do getline you get that newline left after the "y".

You can remove this by using the ignore function:

cout<<"\n\nwant to tell me more? Enter \"y\" for YES and \"n\" for NO\n\n"; cin>>answer; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); cout<<"\n"; 
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! I actually inserted cin.ignore() underneath: cout << "\n\nTell me something about yourself: "; getline (cin, astring); for some crazy reason!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.