istringstream - 怎么做?

9

我有一个文件:

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",我不知道怎么使用istringstream,但我必须使用它。请帮忙!

4个回答

8
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;
< p > istringstream会复制你给它的字符串。它看不到line的变化。要么构建一个新的字符串流,要么强制它获取字符串的新副本。


我本来希望不是这种情况,但我在循环中添加了iss2,以便每次重新初始化,这样就可以正常工作了。谢谢。 - Aaron McKellar
4
在使用iss.str(line)设置新的字符串后,始终调用iss.clear()非常重要,以确保iss流对象已被清空并可以被重新填充。 - phunehehe
如果我想打印每行的三个元素,并且在每行中,分隔符是逗号 , 而不是空格 ,我应该改变什么? - Milan

8
您也可以通过使用两个 while 循环来完成这个操作。
while ( getline(file, line))
{
    istringstream iss(line);

    while(iss >> term)
    {
        cout << term<< endl; // typing all the terms
    }
}

5
这段代码片段使用单个循环提取令牌。
#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);
}

0

hmofrad非常简单而优雅地解决了它。 如果我们放弃使用istringstream,还有另一种解决指定问题的方法:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main(int argc, char **argv) {

if(argc != 2) {
    return(1);
}

string file = argv[1];

ifstream fin(file.c_str());
string q[4]; int a[4]; int b[4];
for (int i=0;i<4;i++)
{
    fin >> q[i];
    fin >> a[i];
    fin >> b[i];
}

for (int i=0;i<4;i++)
{
    cout << q[i] << "\t" << a[i] << "\t" << b[i] << endl;
}
fin.close();
return(0);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接