Do / while循环无法正常运行

时间:2013-01-15 09:12:26

标签: c++

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

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

1 个答案:

答案 0 :(得分: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";