C++ istringstream - 如何做到这一点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2323929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
istringstream - how to do this?
提问by Aaron McKellar
I have a file:
我有一个文件:
a 0 0
b 1 1
c 3 4
d 5 6
Using istringstream, I need to get a, then b, then c, etc. But I don't know how to do it because there are no good examples online or in my book.
使用istringstream,我需要得到a,然后是b,然后是c,等等。但是我不知道怎么做,因为网上或我的书中都没有很好的例子。
Code so far:
到目前为止的代码:
ifstream file;
file.open("file.txt");
string line;
getline(file,line);
istringstream iss(line);
iss >> id;
getline(file,line);
iss >> id;
This prints "a" for id both times. I don't know how to use istringstream obviously and I HAVE to use istringstream. Please help!
这两次都为 id 打印“a”。我显然不知道如何使用 istringstream,我必须使用 istringstream。请帮忙!
回答by ephemient
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
copies the string that you give it. It can't see changes to line
. Either construct a new string stream, or force it to take a new copy of the string.
istringstream
复制你给它的字符串。它看不到line
. 要么构造一个新的字符串流,要么强制它获取字符串的新副本。
回答by Ahmad Khwileh
You could also do this by having two while loops :-/ .
您也可以通过两个 while 循环来做到这一点 :-/ 。
while ( getline(file, line))
{
istringstream iss(line);
while(iss >> term)
{
cout << term<< endl; // typing all the terms
}
}
回答by hmofrad
This code snippet extracts the tokens using a single loop.
此代码片段使用单个循环提取令牌。
#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;
}
fin.close();
return(0);
}