0

この関数の入力タイプでエラーが発生するたびに、*_cost の値が自動的に 0 に設定されます。これはなぜですか?

void Item::setCost(string input){
float entered;
istringstream stin;
stin.str(input);
if(!(stin >> entered)){
    do{
        cout << "invalid input" << endl;
        stin.clear();
        getline(cin, input);
        stin.str(input);
        *_cost = entered;
    }
    while(!(stin >> entered));
}
else{
    *_cost = entered;
}
}

次のようにメイン関数で関数を使用します。

istringstream stin;
string input;

cout << "enter cost" << endl;
getline(cin, input);
items[i]->setCost(input);
4

3 に答える 3

1

*_costif ステートメントのために、常に誤った値になる値に設定しています。
この*_cost = entered行は、プログラムが「無効な入力」コードを通過しているときにのみ実行されます。入力が正当な値でない場合、プログラムは「無効な入力」のみを出力します。したがって、_cost は不正な値にしか設定できません。
問題を解決するには*_cost = entered、do-while ループの後に を置きます。

標準入力を std::string のインスタンスに変換してから istringstream に変換するのではなく、 std::cin を使用してデータを直接読み取るだけではない理由がわかりません。

于 2013-10-29T03:30:33.287 に答える
1

最初のステートメントをブロック*_cost = enteredの外に移動して、その後の最初のステートメントにする必要があります。do .. whileこれを行うと、必須ではありませんが、さらに役立つリファクタリングが表示されます。

while(!(stin >> entered))
{
    cout << "invalid input" << endl;
    stin.clear();
    getline(cin, input);
    stin.str(input);
}
*_cost = entered;
于 2013-10-29T03:34:52.057 に答える