如何从标准输入中检测格式化输入错误?
How to detect formatted input errors from standard input?
尝试输入如下内容时:
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;
}
相关文章:
- 从格式化输入操作中获取读取字符数
- 如何从标准输入中检测格式化输入错误?
- 如何读取和处理格式化的日期,如 01/11/1998、星期日(10000 个输入)C++
- 是否可以使用一行代码从 std::cin 中提取格式化输入
- 在列中格式化输出(用户输入)
- 如何读取时间输入并格式化输出
- 未格式化/格式化的输入
- 如何格式化重载的 c++ 输入运算符
- 在C++中解析格式化的用户输入
- 解析格式化输入时划分单词时出现问题
- 如何使用 getline 和字符串流来解析格式化的日期和时间输入
- std::getline()从流中读取格式化的输入后读取错误的数据
- 来自 std::vector <double>的未格式化流输入
- 使用cin读取格式化输入
- 如何确定未格式化输入函数读取的字符数
- 正在重新格式化输入的带有空格的字符串
- 扫描 读取格式化输入
- c++中字符串的格式化输入
- 在c++中从格式化输入切换到非格式化输入
- 格式化输入 - scanf 的C++版本是什么?