istringstream - 怎么做?

Aar*_*lar 4 c++ file-io

我有一个文件:

a 0 0
b 1 1
c 3 4
d 5 6
Run Code Online (Sandbox Code Playgroud)

使用istringstream,我需要得到一个,然后是b,然后是c,等等.但我不知道该怎么做,因为在网上或我的书中没有好的例子.

代码到目前为止:

ifstream file;
file.open("file.txt");
string line;

getline(file,line);
istringstream iss(line);
iss >> id;

getline(file,line);
iss >> id;
Run Code Online (Sandbox Code Playgroud)

这两次都会为id打印"a".我不知道如何使用istringstream,我必须使用istringstream.请帮忙!

eph*_*ent 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;
Run Code Online (Sandbox Code Playgroud)

istringstream复制您提供的字符串.它无法看到变化line.构造新的字符串流,或强制它获取字符串的新副本.

  • 在使用`iss.str(line)`设置新字符串后,始终调用`iss.clear()`非常重要 (4认同)

小智 6

您也可以通过两个 while 循环来做到这一点 :-/ 。

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

    while(iss >> term)
    {
        cout << term<< endl; // typing all the terms
    }
}
Run Code Online (Sandbox Code Playgroud)


hmo*_*rad 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);
}
Run Code Online (Sandbox Code Playgroud)