我正在读取一个用 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
方法设置“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/