我正在做一个项目,我需要检查输入是否正确 (n),我目前有一些代码不允许输入字符串,因为它会再次要求输入正确的数量。我在编写不允许 float 通过的代码时遇到问题,因为它目前只是忽略了输入的浮点部分。如果这是一个简单的问题,我很抱歉,但我还没有找到解决这个问题的方法。
for(int i=0; i<1; ++i)
{
string b1;
int e;
do
{
getline(cin,b1);
e=atoi(b1.c_str());
}
while(e==0 && b1!="0");
n=e; // where n is the user input
}
最佳答案
假设您考虑任何带有小数点 ('.'
) 或使用带负指数的科学记数法作为 Not Acceptable float ,只需检查输入的字符串是否包含以下之一:
std::string::iterator it;
if (b1.end() != std::find(b1.begin(), b1.end(), '.')
|| (b1.end() != (it = std::find_if(b1.begin(), b1.end(),
[](char c){ return c == 'e' || c == 'E'; })
&& it + 1 != b1.end()
&& '-' == it[1])) {
// deal with the string being a floating point number with a fractional part
}
请注意,这会将例如 "10e-1"
视为错误值,尽管它实际上只是 "1"
的奇特拼写。
关于c++ - 一种不接受 float 作为输入的方法 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33986621/