验证c++中的浮点值
Validation for float in c++
我以浮点形式获取输入。例如,如果用户在3.5中输入,那么它可以正常工作。如果用户输入3.X或任何其他字符,则会导致无限循环。有没有什么方法可以验证变量,让用户只输入数字?我使用的是gcc编译器。
通常的方法是将数据作为字符串读取,然后将其转换为浮点值,然后查看整个输入字符串在该转换中的消耗情况。Boost lexical_cast
(举一个例子)可以为您实现大部分自动化。
您没有给出任何示例代码,所以我们可以看到您在做什么,但我从症状中怀疑你在做什么:
while ( ! input.eof() ) {
double d;
input >> d;
// do someting with d...
}
这有两个问题:第一个问题是一旦出现错误(因为'X'
不能是double
的一部分),流存储错误,直到它被明确清除,所以所有后续输入也会失败(并且不再从字符串中提取其他字符)。当你流中存在格式错误,有必要重置该错误状态,然后继续。
以上的第二个问题是input.eof()
并不意味着直到输入失败;这不是一个很有用的函数。你可能想做的是:
double d;
while ( input >> d ) {
// do something with d
}
这将在出现第一个错误时停止读取。如果您想从错误并继续,那么您需要更详细的东西:
double d;
while ( input >> d || !input.eof() ) {
if ( input ) {
// do something with d...
} else {
// format error...
input.clear(); // reset the error state...
// advance the stream beyond the error:
// read to next white space (or EOF), or at least
// advance one character.
}
}
或者,按照其他人的建议,它通常更稳健,逐行读取输入,然后扫描行:
std::string line;
while ( std::getline( input, line ) ) {
std::istringstream l( line );
double d;
if ( l >> d >> std::ws && d.get() == EOF ) {
// do something with d...
} else {
// format error...
// we don't have to clear or skip ahead, because we're
// going to throw out the istringstream anyway, and the
// error didn't occur in the input stream.
}
}
这强加了一个更严格的格式:每行一个值,但如果你计算了行数,就可以输出错误中的行号消息必须纠正错误输入的人会很感激那个
try
{
double x = boost::lexical_cast<double>(str); // double could be anything with >> operator.
}
catch(...) { oops, not a number }
from:如何用C++确定字符串是否为数字?
从输入中读取双值并确保其格式正确的最佳方法是将输入读取为字符串,然后使用stdlib
库中包含的标准strtod
函数对其进行解析。
有关解析该字符串时一些不同可能性的更详细解释,您可以查看另一篇文章。
你的帖子我有点不清楚,但据我所知,我认为你应该使用strtof
。以字符串的形式从用户那里获取数据,然后使用该函数转换为float,并通过比较指针来检查是否成功。
有关更多信息,请查看strtof
的手册页。
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- LibGit2 SSH身份验证失败
- Vulkan验证层不断在VkQueuePresentKHR()上抛出图像布局错误
- constexpr上下文中std::initializer_list的验证
- 正在验证c++中用户的整数输入
- 加密++验证大文件签名
- C++卡验证问题
- 验证指针链
- 此代码验证公式是什么意思?
- cin 的十进制输入验证?
- 简单的 HTML 验证器
- 密码长度验证 (c++)
- 输入验证以筛选出字符、字符串和一系列整数
- 如何使用 CredUIPromptForWindowsCredentials验证凭据
- 指针验证的最佳实践?
- RSA_PKCS1签名验证
- 验证openssl c++中的签名,这是由JAVA DSA签名的?
- 使用 C++ 验证 NMEA 句子
- 为什么 WinInet 在通过 FQDN 连接时无法通过协商自动进行身份验证,但如果通过 IP 连接则成功?