0

このプログラムでユーザーに数字の代わりにテキストを入力させるにはどうすればよいですか? テキストを受け入れる cin ステートメントを取得するにはどうすればよいですか? char を使用する必要がありますか?

int main()
{
    using namespace std;
    int x = 5;
    int y = 8;
    int z;
    cout << "X=" << x << endl;
    cout << "Y=" << y << endl;
    cout << "Do you want to add these numbers?" << endl;
    int a;
    cin >> a;
    if (a == 1) {
        z = add(x, y);
    }
    if (a == 0) {
        cout << "Okay" << endl;
        return  0;
    }
    cout << x << "+" << y << "=" << z << endl;
    return 0;
}

---編集--- なぜこれが機能しないのですか?

int main()
{
    using namespace std;
    int x = 5;
    int y = 8;
    int z;
    cout << "X = " << x << " Y = " << y << endl;
    string text;
    cout << "Do you want to add these numbers together?" << endl;
    cin >> text;
    switch (text) {
        case yes:
            z = add(x, y);
            break;
        case no: cout << "Okay" << endl;
        default:cout << "Please enter yes or no in lower case letters" << endl;
            break;
}
    return 0;
}

みんなありがとう!興味のある方は、ここで私が作ったゲームをチェックしてみてください。 http://pastebin.com/pmCEJU8E あなたは若いプログラマーが夢を実現するのを手伝っています。

4

3 に答える 3

2

あなたはstd::stringその目的のために使うことができます。cin空白になるまでテキストを読み取るRemeber 。行全体を読みたい場合getlineは、同じライブラリの関数を使用してください。

于 2013-03-02T15:57:14.187 に答える
0

Do you want to add these numbers?によって連結される可能性があるため、ユーザーからの1文字のみの応答に関心があるため、1文字のみを読み取る場合は(Y/N)、(私の意見では) getchar()関数を使用する必要があります。これは、エラーが発生しやすい1文字の入力処理に対して行う方法です。

bool terminate = false;
char choice;
while(terminate == false){
    cout << "X=" << x << endl;
    cout << "Y=" << y << endl;
    cout << "Do you want to add these numbers?" << endl;

    fflush(stdin);
    choice = getchar();
    switch(choice){
    case 'Y':
    case 'y':
        //do stuff
        terminate = true;
        break;
    case 'N':
    case 'n':
        //do stuff
        terminate = true;
        break;
    default:
        cout << "Wrong input!" << endl;
        break;
    }
}

編集への返信として

std::stringに引数として渡すことができないため、これは機能しませんswitch。先ほど言ったように、そのためには 1 文字だけを読む必要があります。文字列の使用を主張する場合は、 を使用せず、文字列コンパレータ を使用してブロックを選択してswitchください。if else==

cin >> text;
if(text == "yes"){
    z = add(x, y);
}
else if(text == "no")
{
    cout << "Okay" << endl;
}
else
{
    cout << "Please enter yes or no in lower case letters" << endl;
}
于 2013-03-02T16:09:54.530 に答える
0

使用できますstd::string

std::string str;
std::cin>>str; //read a string 

// to read a whole line
std::getline(stdin, str);
于 2013-03-02T15:55:30.263 に答える