我有一个文件:
a 0 0
b 1 1
c 3 4
d 5 6
使用istringstream,我需要得到a,然后是b,然后是c,等等。但是我不知道怎么做,因为在线或在我的书中没有好的例子。
到目前为止代码:
ifstream file;
file.open("file.txt");
string line;
getline(file,line);
istringstream iss(line);
iss >> id;
getline(file,line);
iss >> id;
这两次都会为id打印“a”。我不知道如何使用istringstream,我必须使用istringstream。请帮忙!
答案 0 :(得分:6)
ifstream file;
file.open("file.txt");
string line;
getline(file,line);
istringstream iss(line);
iss >> id;
getline(file,line);
istringstream iss2(line);
iss2 >> id;
getline(file,line);
iss.str(line);
iss >> id;
istringstream
复制您提供的字符串。它看不到line
的更改。构造一个新的字符串流,或强制它获取该字符串的新副本。
答案 1 :(得分:3)
你也可以通过两个while循环来做到这一点: - /。
while ( getline(file, line))
{
istringstream iss(line);
while(iss >> term)
{
cout << term<< endl; // typing all the terms
}
}
答案 2 :(得分:0)
此代码段使用单个循环提取标记。
#include <iostream>
#include <fstream>
#include <sstream>
int main(int argc, char **argv) {
if(argc != 2) {
return(1);
}
std::string file = argv[1];
std::ifstream fin(file.c_str());
char i;
int j, k;
std::string line;
std::istringstream iss;
while (std::getline(fin, line)) {
iss.clear();
iss.str(line);
iss >> i >> j >> k;
std::cout << "i=" << i << ",j=" << j << ",k=" << k << std::endl;
}
return(0);
}