有可能像这样串流吗?我正在尝试用ifstream阅读并转换它。
string things = "10 11 12 -10";
int i1;
int i2;
int i3;
int i4;
stringstream into;
into << things;
into >> i1;
into >> i2;
into >> i3;
into >> i4;我期望它是:
i1 = 10
i2 = 11
i3 = 12
i4 = -10对吗?
同一个stringstream变量可以多次使用吗?
当我尝试的时候,第一次是可以的,但后来的一切都是0。
发布于 2011-02-20 13:24:17
这肯定能行得通。您甚至可以混合类型,如下所示:
string things = "10 Nawaz 87.87 A";
int i;
std::string s;
float f;
char c;
stringstream into;
into << things;
into >> i >> s >> f >> c; //all are different types!
cout << i <<" "<< s <<" "<< f <<" "<< c;输出:
10 Nawaz 87.87 A在ideone上演示:http://www.ideone.com/eb0dR
发布于 2011-02-20 13:18:33
它起作用了吗?我这样做的方式是:
istringstream into(things);
into >> i1;诸若此类。这将产生您发布的输出。
发布于 2011-02-20 13:28:38
您发布的内容与Jeremiah使用istringstream的解决方案一起工作。但是也可以考虑使用scanf系列的函数(对于几个int来说没有太大的区别,但是对于更高级的输入,使用scanf可能比摆弄流操纵器简洁得多):
string things = "10 11 12 -10";
int i1, i2, i3, i4, i5, i6;
sscanf(things.c_str(), "%d %d %d %d", &i1, &i2, &i3, &i4);您的示例在那之后只给出0的原因是因为一旦提取-10,stringstream缓冲区就是空的:在提取更多之前,您必须在缓冲区中插入更多。您可以多次使用同一个stringstream实例,但每次都需要充分使用缓冲区,或者在向缓冲区中插入下一项之前认识到缓冲区中还有更多内容:
string things = "10 11 12 -10", temp;
int i1, i2, i3, i4;
stringstream into;
into << things; //buffer is now "10 11 12 -10"
into >> i1; //buffer is now " 11 12 -10"
into >> i2; //" 12 -10"
into >> i3; //" -10"
into >> i4; //""
//more code here...
//come back and use the instance again
into << "more: 1 2 3"; //"more: 1 2 3"
into >> temp; //temp is "more:"; into's buffer is " 1 2 3"
into >> i1; //buffer is " 2 3"
//more code here...
//reuse into once again
into << "4 5 6"; // buffer is now " 2 3 4 5 6"
into >> i1; //i1 gets the 2 from before, not the 4 just inserted; buffer now " 3 4 5 6"
into >> i2; //i2==3; buffer is " 4 5 6"此外,ios ( stringstream继承自它)还定义了!操作符和到void*的强制转换,以便您可以方便地检查提取是否失败(从技术上检查是否设置了failbit或badbit,我相信当缓冲区中没有足够的内容时,failbit将与eofbit一起设置):
string things = "10 11 12 -10";
int i1, i2, i3, i4;
stringstream into;
into << things;
into >> i1 >> i2 >> i3 >> i4;
if (into >> i5) {
cout << "extraction to i5 succeeded" << endl;
}
if (!(into >> i6)) {
cout << "extraction to i6 failed" << endl;
}https://stackoverflow.com/questions/5055381
复制相似问题