如何从标准输入中检测格式化输入错误?

How to detect formatted input errors from standard input?

本文关键字:格式化 输入 错误 检测 标准输入      更新时间:2023-10-16

尝试输入如下内容时:

Please enter the number of elements: 4
Enter the list to be sorted: 4 x3 1 6

我得到的输出为:

The sorted list is:error: invalid input

我怎样才能做到,如果出现错误,则仅执行错误无效的输入语句,反之亦然?

#include <iostream>
using namespace std;
int main()
{
int a[50], n, i, j, temp;
cout << "Please enter the number of elements:";
cin >> n;
cout << endl;
cout << "Enter the list to be sorted:"; 
cout << endl;
if (cin >> n) 
{
for (i = 0; i < n; ++i)
cin >> a[i];
for (i = 1; i < n; ++i)
{
for (j = 0; j < (n - i); ++j)
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
cout << "The sorted list is:";
for (i = 0; i < n; ++i)
cout << " " << a[i];
}
else (!(cin >> n));
{
cout << "error: invalid input" << endl;
}
return 0;
}

您可以执行类似操作以进行错误检查。

1(要求用户在获得尺寸后输入数字。 2(首先将这些数字存储为字符,使用函数isdigit((检查用户输入是否正确。

while (A[i].isdigit() == false) // if it is not a number
cout<<"Enter again : "

3( 转换这些字符并将它们存储在数组中,如果输入的数字正确。

希望这有帮助。

您正在从cin中读取两次n。在if测试中cin您应该只检查cin,即

`if (cin)`

第二个问题是你的else块

else (!(cin >> n));
{
cout << "error: invalid input" << endl;
}

尽管格式化是

else
{
// 'n' read from cin, return value negated and discarded
(!(cin >> n))
}
// always executed
cout << "error: invalid input" << endl;

我想cin应该在评论中

else // (!(cin >> n));
{
cout << "error: invalid input" << endl;
}