0

do/whileループを正しく機能させるのに問題があります。このプログラムは最初の回避策としては問題なく動作しますが、「もっと教えたい」かどうかを尋ねられたときに「y」と入力すると、プログラムはユーザーに質問をして(文字列を入力できないようにします)、ステートメント。私は何が間違っているのですか?どうすれば正しく機能させることができますか?

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

1 に答える 1

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";
于 2013-01-15T09:16:26.563 に答える