7
cout << "How many questions are there going to be on this exam?" << endl;
cout << ">>";
getline(cin, totalquestions);

この小さなコードは、私が作成したクラスの関数からのものでありtotalquestions、for ループを実行して、私が尋ねた質問の合計量を尋ね続けることができるように、int にする必要があります。

question q;
for(int i = 0; i < totalquestions; i++)
{
    q.inputdata();
    questions.push_back(q);
}

このコードはどこで機能しますか? 誰かがこれを機能させるためのアイデアを持っていますか?

4

5 に答える 5

12

使用する

cin >> totalquestions;

エラーもチェック

if (!(cin >> totalquestions))
{
    // handle error
}
于 2011-04-30T20:06:08.397 に答える
3

getline行全体を文字列として読み取ります。それでもintに変換する必要があります:

std::string line;
if ( !std::getline( std::cin, line ) ) {
//  Error reading number of questions...
}
std::istringstream tmp( line );
tmp >> totalquestions >> std::ws;
if ( !tmp ) {
//  Error: input not an int...
} else if ( tmp.get() != EOF ) {
//  Error: unexpected garbage at end of line...
}

std::cinに直接 入力するだけでは機能しないtotalquestionsことに注意してください。末尾の 文字がバッファに残り、次のすべての入力が非同期になります。に呼び出しを追加することでこれを回避することは可能ですが、ゴミが残っているため、エラーを見逃すことになります。行指向の入力を行う場合は、に固執し、必要な変換に使用します。'\n'std::cin.ignoregetlinestd::istringstream

于 2011-04-30T23:48:26.457 に答える
3

これを行う:

int totalquestions;
cout << "How many questions are there going to be on this exam?" << endl;
cout << ">>";
cin >> totalquestions;

Getline は をつかむためのものですchars。で実行できますがgetline()cinはるかに簡単です。

于 2011-04-30T20:05:53.560 に答える
1

使用しないでくださいgetline:

int totalquestions;
cin >> totalquestions;
于 2011-04-30T20:05:34.613 に答える
1

ユーザーからintを取得するより良い方法の1つ:-

#include<iostream>
#include<sstream>

int main(){
    std::stringstream ss;

    ss.clear();
    ss.str("");

    std::string input = "";

    int n;

    while (true){
        if (!getline(cin, input))
            return -1;

        ss.str(input);

        if (ss >> n)
            break;

        std::cout << "Invalid number, please try again" << std::endl;

        ss.clear();
        ss.str("");
        input.clear();
}

cin >> n を使用するよりも優れているのはなぜですか?

その理由を説明する実際の記事

あなたの質問に関しては、上記のコードを使用して int 値を取得し、それをループで使用します。

于 2015-11-25T15:34:04.490 に答える