gpt4 book ai didi

c++ - 用户输入数字+字符时出错

转载 作者:行者123 更新时间:2023-11-30 04:04:55 29 4
gpt4 key购买 nike

这是我的代码,当用户输入不是数字时显示错误。但是,当用户输入字母数字(例如:123abc)时,它会重复错误消息两次。

#include <iostream>
using namespace std;

int main()
{
int option;

do
{
cout <<"Type random characters ( E.g : asdwefef ) " ;
cin >> option;

if (cin.good()) // If numeric
{

}
else
{
cout << "Invalid input!" << endl;
cin.clear(); // Clear buffer
cin.ignore( INT_MAX, '\n' );
}

}while (option != 0);

return 0;
}

我该如何解决?我尝试使用以下方法,但结果是一样的。

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

最佳答案

输入流一个一个地解析字符。对于数字提取,流将不断读取字符,直到找到一个非数字字符。这不会设置 std::ios_base::failbit如果它已经成功地将字符写入其操作数,并且没有尝试读取非数字字符。因此,std::cin.good()将返回 true第一次迭代。

一般来说,检查good()不是评估流有效性的首选方法。 Streams 有一个内部 bool 运算符可以为您执行此操作。您所要做的就是将实际的输入操作包含在一个 bool 表达式中:

if (std::cin >> option) {
// successful input
}
else {
// unsuccessful
}

现在,要检查整个 输入是否为数字,最好读入一个字符串并手动进行解析,因为流无法自行执行此操作(默认情况下)。或者,要让流自己执行此操作,您可以创建自定义的 std::num_get<char>如果可以确定输入不完全是数字,则设置错误掩码的方面。这个方面将被安装到流的语言环境中;您可以随时通过更改为原始版本来卸载它:

class num_get : public std::num_get<char>
{
public:
iter_type do_get( iter_type it, iter_type end, std::ios_base& str,
std::ios_base::iostate& err, long& v) const
{
auto& ctype = std::use_facet<std::ctype<char>>(str.getloc());
it = std::num_get<char>::do_get(it, end, str, err, v);

if (it != end && !(err & std::ios_base::failbit)
&& ctype.is(ctype.alpha, *it))
err |= std::ios_base::failbit;

return it;
}
};

将其安装到语言环境和 imbue()语言环境到流中以获得所需的行为:

std::locale original_locale(std::cin.getloc());
std::cin.imbue(std::locale(original_locale, new num_get));

if (std::cin >> option) {
// input was entirely numeric
}
else {
// input was not entirely numeric
}

关于c++ - 用户输入数字+字符时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23583733/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com