2013-01-15 186 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