2

1.w に入ると次の検証コードが cin.ignore でスタックし、w.1 に入ると無限ループに入るのはなぜですか?
数値入力を検証するコードを作成しようとしています。他の投稿での提案からコードを作成しましたが、まだ問題があります。

//The code is validation code used to check if input is numerical (float or integer). 
#include <iostream>
#include <string>
#include <limits> // std::numeric_limits
using namespace std;
int main ()
{
    string line;
    float amount=0;
    bool flag=true;

//while loop to check inputs
while (flag){ //check for valid numerical input
    cout << "Enter amount:";
    getline(cin>>amount,line);
//use the string find_first_not_of function to test for numerical input
    unsigned test = line.find_first_not_of('0123456789-.');

    if (test==std::string::npos){ //if input stream contains valid inputs
        cout << "WOW!" << endl;
        cout << "You entered " << line << endl;
        cout << "amount = " << amount << endl;
    }

    else{ //if input stream is invalid
        cin.clear();
        // Ignore to the end of line
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
  }

    return 0;
}
4

1 に答える 1

3

まず、'0123456789-.'する必要があります"0123456789-."(二重引用符に注意してください)。前者はマルチバイト文字リテラルです。

入力時1.w:

  • 1によって抽出されcin>>amountます。
  • .wによって抽出されるgetline
  • ストリームは空なのでignore、入力を待ちます

入力時w.1:

  • cin>>amount失敗し、failbit設定されます
  • getlineストリームが悪い場合は抽出できないため、line空のままです
  • testequalsであるため、ストリームをクリアするnposためにブロックに入ることはありませんelse
  • 何度も繰り返す
于 2013-04-20T07:06:06.460 に答える