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

时间:2015-01-07 04:29:25

标签: c++ string parsing double text-files

我正在阅读文本文件并通过解析(逐行)提取它的信息。 以下是文本文件的示例:

 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

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

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

2 个答案:

答案 0 :(得分:1)

你可以这样做:

// check for integer

std::string s = "42";

int i;
if((std::istringstream(s) >> i).eof())
{
    // number is an integer
    std::cout << "i = " << i << '\n';
}

// check for real

s = "4.2";

double d;
if((std::istringstream(s) >> d).eof())
{
    // number is real (floating point)
    std::cout << "d = " << d << '\n';
}

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

答案 1 :(得分:0)

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

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.