[英]how to extract specific integers in a mixed string-integer line in c++
I am reading a text file in c++, this is example of some lines in it: 我正在用C ++阅读文本文件,这是其中一些行的示例:
remove 1 2 cost 13.4
How could I disregard all things except two integers after remove, "1" and "2" and put them in two integer variable? 在删除“ 1”和“ 2”之后,如何忽略除两个整数以外的所有东西,并将它们放入两个整数变量中?
my incomplete code: 我不完整的代码:
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
}
}
}
Here are a few options: 以下是一些选择:
Use the stringstream
created for the line to find the remove
token and parse the next two integers. 使用为该行创建的stringstream
查找remove
令牌并解析接下来的两个整数。 In other words, replace this: 换句话说,替换为:
if (line.find("remove") != string::npos) { iss >> a >> b; // this obviously does not work, not sure how to // write the code here }
with this: 有了这个:
string token; iss >> token; if (token == "remove") { iss >> a >> b; }
Create a stringstream
for the rest of the line ( 6
is the length of the "remove" token). 为该行的其余部分创建一个stringstream
( 6
是“删除”令牌的长度)。
string::size_type pos = line.find("remove"); if (pos != string::npos) { istringstream iss(line.substr(pos + 6)); iss >> a >> b; }
Call the seekg
method on the line stringstream
to set the input position indicator of the stream after the "remove" token. 在行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.