2013-01-15 150 views
0

我有一个问题让我的do/while循环正常工作。 这个程序运行良好的第一个复飞,但是当我输入'Y'时,当它询问我是否想“告诉更多”该程序只是询问用户的问题(不允许我输入一个字符串),然后couts声明。我究竟做错了什么?以及如何让它正常运作?做/ while循环无法正常工作

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; 
} 
+0

一开始,我会放一些代码来检查,如果答案== y或(我让你查找如何这样做),因为如果用户的大写锁定,那么do/while循环将会失败。 –

+0

将其缩小为[简短的自包含正确示例](http://sscce.org/)。 –

回答

4

输入操作>>是这样的:首先,它跳过空格,如果有的话;然后它读取字符串,直到它到达下一个空格,在你的情况下,在'y'之后的换行符。然后这条换行符留在流中,所以当你在循环开始时执行getline时,你会在"y"之后得到该换行符。

您可以通过使用ignore函数删除此:

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"; 
+0

谢谢!我实际上在下面插入了cin.ignore():cout <<“\ n \ n告诉我关于你自己的一些事情:”; getline(cin,astring);出于某种疯狂的原因! – user1979708