c++ - 如何在 C++ 中的混合字符串整数行中提取特定整数

标签 c++ string

我正在读取一个用 C++ 编写的文本文件,这是其中一些行的示例:

remove 1 2 cost 13.4

如何在删除后忽略除两个整数“1”和“2”之外的所有内容并将它们放入两个整数变量中?

我的不完整代码:

ifstream file("input.txt");
string line;
int a, b;

if(file.is_open())
{
   while (!file.eof())
   {
      getline (file, line);
      istringstream iss(line);
      if (line.find("remove") != string::npos)
      {     

          iss >> a >> b;      // this obviously does not work, not sure how to
                              // write the code here
      }
   }

}

最佳答案

这里有几个选项:

  1. 使用为该行创建的stringstream 找到remove 标记并解析接下来的两个整数。换句话说,替换为:

    if (line.find("remove") != string::npos)
    {     
    
        iss >> a >> b;      // this obviously does not work, not sure how to
                            // write the code here
    }
    

    用这个:

    string token;
    iss >> token;
    
    if (token == "remove")
    {
        iss >> a >> b;
    }
    
  2. 为该行的其余部分创建一个 stringstream(6 是“删除”标记的长度)。

    string::size_type pos = line.find("remove");
    
    if (pos != string::npos)
    {     
        istringstream iss(line.substr(pos + 6));
    
        iss >> a >> b;
    }
    
  3. 调用stringstream行的seekg方法设置“remove”token之后流的输入位置指示符。

    string::size_type pos = line.find("remove");
    
    if (pos != string::npos)
    {     
        iss.seekg(pos + 6);
    
        iss >> a >> b;
    }
    

关于c++ - 如何在 C++ 中的混合字符串整数行中提取特定整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21590019/

相关文章:

.net - 帮助调试 Interop 问题的最佳工具

string - 是否有正则表达式可以切换字符串中的字符大小写?

javascript - 在 JS 中查询 boolean 变量与比较两个字符串

javascript - for() 循环比较两个数组,然后更改另一个数组。仅 JavaScript

python - 删除 Python 字符串中的第一个单词?

C++模板类继承,如何规范成员类型?

c++ - 模板化类中的模板函数

c++ - 标准是否防止在可变参数模板中缩小具有足够小的文字值的文字转换

c++ - funsafe-math-optimizations,两行不同的公式,不同的结果

Ruby - 如何检查字符串是否包含数组中的所有单词?