验证c++中的浮点值

Validation for float in c++

本文关键字:c++ 验证      更新时间:2023-10-16

我以浮点形式获取输入。例如,如果用户在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的手册页。