【问题标题】:Distinguishing between numbers and other symbols [c++]区分数字和其他符号 [c++]
【发布时间】:2015-03-04 22:22:04
【问题描述】:

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

 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++。

【问题讨论】:

  • 用正则表达式怎么样?
  • 上网查一下。
  • 你可能想看看这个stackoverflow.com/questions/2926878/…
  • @kuisf-rund 您可以使用正则表达式来搜索文本中的模式。
  • 您可以尝试将其转换为双精度,如果失败则将其保留为字符串 try { double x = mystring; } catch() { string x = mystring; }

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


【解决方案1】:

你可以这样做:

// 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() 检查确保数字后面没有非数字字符。

【讨论】:

    【解决方案2】:

    假设当前的 (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.
    

    【讨论】:

      猜你喜欢
      • 2012-10-07
      • 2023-03-05
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多