Do/while循环不能正常工作

Do/while loop not functioning correctly

本文关键字:工作 常工作 while 循环 不能 Do      更新时间:2023-10-16

我有一个问题,让我的do/while循环正常工作。这个程序在第一次循环时运行良好,但是当我输入"y"时,当它问我是否想"告诉更多"时,程序只是问用户这个问题(不允许我输入字符串),然后计算语句。我做错了什么?我怎样才能让它正常工作呢?

using namespace std;
int main()
{
    int i, numspaces = 0;
    char nextChar;
    string trimstring;
    string uc, rev;
    string answer;
    char temp;
    cout << "nn John Acosta"
    <<" Exercise 1n"
    << "nn This program will take your string, count the numbern"
    << " of chars and words, UPPERCASE your string, and reverse your string.";
    string astring;
    do {
        cout << "nnTell 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 << "ntYou Entered: " << astring
        << "ntIt has "<<trimstring.length()
        << " chars and "<<numspaces+1
        << " words."
        << "ntUPPERCASE: "<<uc
        << "ntReversed: "<<rev
        << "nn";

        cout<<"nnwant to tell me more? Enter "y" for YES and "n" for NOnn";
        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;
}

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

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

cout<<"nnwant to tell me more? Enter "y" for YES and "n" for NOnn";
cin>>answer;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
cout<<"n";