区分数字和其他符号 [c++]

Distinguishing between numbers and other symbols [c++]

本文关键字:c++ 符号 其他 数字      更新时间:2023-10-16

我正在读取一个文本文件,并通过解析(逐行)提取其中的信息片段。下面是文本文件的示例:

 0    1.1       9     -4
 a    #!b     .c.     f/ 
a4   5.2s   sa4.4   -2lp

到目前为止,我能够使用空格' '分隔符来拆分每行。因此,例如,我可以将"1.1"的值保存到字符串变量中。

我想做的(这就是我卡住的地方)是确定我正在阅读的信息是否代表一个数字。使用前面的示例,这些字符串不表示数字:a #!b .c. f/ a4 5.2s sa4.4 -2lp或者,这些字符串确实表示数字:0 1.1 9 -4

然后我想将表示数字的字符串存储到双精度类型变量中(我知道如何转换为双精度部分)。

那么,如何区分数字和其他符号呢?我正在使用c ++。

你可以这样做:

// check for integer
std::string s = "42";
int i;
if(!s.empty() && (std::istringstream(s) >> i).eof())
{
    // number is an integer
    std::cout << "i = " << i << 'n';
}
// check for real
s = "4.2";
double d;
if(!s.empty() && (std::istringstream(s) >> d).eof())
{
    // number is real (floating point)
    std::cout << "d = " << d << 'n';
}

eof()检查确保数字后没有非数字字符。

假设当前(C++11)编译器,处理此问题的最简单方法可能是使用std::stod进行转换。您可以为此传递一个size_t的地址,该地址指示在转换为双精度时无法使用的第一个字符的位置。如果整个输入转换为双精度,它将是字符串的末尾。如果是任何其他值,则至少部分输入未转换。

size_t pos;
double value = std::stod(input, &pos);
if (pos == input.length())
    // the input was numeric
else
    // at least part of the input couldn't be converted.