c++模板将字符串转换为数字

C++ template converting string to number

本文关键字:转换 数字 字符串 c++      更新时间:2023-10-16

我有以下模板函数:

  template <typename N>
  inline N findInText(std::string line, std::string keyword)
  {
    keyword += " ";
    int a_pos = line.find(keyword);
    if (a_pos != std::string::npos)
    {
      std::string actual = line.substr(a_pos,line.length());
      N x;
      std::istringstream (actual) >> x;
      return x;
    }
    else return -1; // Note numbers read from line must be always < 1 and > 0
  }

看起来像这行:

 std::istringstream (actual) >> x;

是行不通的。但是相同的函数没有模板化:

    int a_pos = line.find("alpha ");
    if (a_pos != std::string::npos)
    {
      std::string actual = line.substr(a_pos,line.length());
      int x;
      std::istringstream (actual) >> x;
      int alpha = x;
    }

工作很好。这是std::istringstream和模板的问题吗??

我正在寻找一种方法来读取配置文件和加载参数,可以是int或real。

编辑解决方案:

template <typename N>
  inline N findInText(std::string line, std::string keyword)
  {
    keyword += " ";
    int a_pos = line.find(keyword);
    int len = keyword.length();
    if (a_pos != std::string::npos)
    {
      std::string actual = line.substr(len,line.length());
      N x;
      std::istringstream (actual) >> x ;
      return x;
    }
    else return -1;
  }

它不起作用,因为您正在读取的字符串不能转换为数字,因此您返回未初始化的垃圾。发生这种情况是因为你读错了字符串——如果linefoo bar 345, keywordbar,那么actual被设置为bar 345,这不会转换为整数。相反,您需要转换345

你应该这样重写你的代码:

    std::string actual = line.substr(a_pos + keyword.length());
    N x;
    if (std::istringstream (actual) >> x)
        return x;
    else
        return -1;

这样,您可以转换正确的子字符串,并且还可以正确处理不能将其转换为整数的情况。