istringstream - how to do this?

假装没事ソ 提交于 2020-01-01 00:22:02

问题


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.

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!


回答1:


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.




回答2:


You could also do this by having two while loops :-/ .

while ( getline(file, line))
{
    istringstream iss(line);

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



回答3:


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;
    }

    return(0);
}


来源:https://stackoverflow.com/questions/2323929/istringstream-how-to-do-this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!