簡體   English   中英

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

[英]how to extract specific integers in a mixed string-integer line in c++

我正在用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. 為該行的其余部分創建一個stringstream6是“刪除”令牌的長度)。

     string::size_type pos = line.find("remove"); if (pos != string::npos) { istringstream iss(line.substr(pos + 6)); iss >> a >> b; } 
  3. 在行stringstream上調用seekg方法,以在“刪除”標記之后設置流的輸入位置指示符。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM