cout << "Enter the number: ";
int number;
if (cin >> number)
{
// throw away the rest of the line
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
cout << "Enter names: ";
string name;
// keep getting lines until EOF (or "bad" e.g. error reading redirected file)...
while (getline(cin, name))
...use name...
}
else
{
std::cerr << "ERROR reading number\n";
exit(EXIT_FAILURE);
}
上記のコードでは、このビット...
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
...数値に空白のみが含まれた後、入力行の残りの部分をチェックします。
無視してみませんか?
これはかなり冗長なので、ignore
後のストリームで使用すること>> x
は、コンテンツを次の改行まで破棄するためによく推奨される代替方法ですが、空白以外のコンテンツを破棄して、ファイル内の破損したデータを見落とすリスクがあります。ファイルのコンテンツが信頼できるかどうか、破損したデータの処理を回避することがどれほど重要かなどに応じて、気にする場合と気にしない場合があります。
では、いつclearを使用して無視しますか?
したがって、std::cin.clear()
(およびstd::cin.ignore()
)はこれには必要ありませんが、エラー状態を削除するのに役立ちます。たとえば、ユーザーに有効な番号を入力する機会を多く与えたい場合です。
int x;
while (std::cout << "Enter a number: " &&
!(std::cin >> x))
{
if (std::cin.eof())
{
std::cerr << "ERROR unexpected EOF\n";
exit(EXIT_FAILURE);
}
std::cin.clear(); // clear bad/fail/eof flags
// have to ignore non-numeric character that caused cin >> x to
// fail or there's no chance of it working next time; for "cin" it's
// common to remove the entire suspect line and re-prompt the user for
// input.
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
スキップなどでもっと簡単にできませんか?
ignore
元の要件に代わるもう1つの単純ですが、中途半端な代替手段は、std::skipws
行を読み取る前に任意の量の空白をスキップするために使用することです...
if (std::cin >> number >> std::skipws)
{
while (getline(std::cin, name))
...
...しかし、「1E6」のような入力を取得した場合(たとえば、1,000,000を入力しようとしている科学者が、C ++は浮動小数点数の表記のみをサポートしている場合)、それを受け入れない場合は、にnumber
設定され1
、次のようにE6
読み取られます。の最初の値name
。これとは別に、有効な番号の後に1つ以上の空白行がある場合、それらの行は黙って無視されます。