![](/img/trans.png)
[英]How to detect you've reached the end of a fgets string of integers, when 0 is the last integer in the line, using 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
}
}
}
以下是一些選擇:
使用為該行創建的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; }
為該行的其余部分創建一個stringstream
( 6
是“刪除”令牌的長度)。
string::size_type pos = line.find("remove"); if (pos != string::npos) { istringstream iss(line.substr(pos + 6)); iss >> a >> b; }
在行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.