您发布的内容与 Jeremiah Willcock 的解决方案一起使用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 的原因是,stringstream
一旦您提取 -10,缓冲区就为空:您必须先在缓冲区中插入更多内容,然后才能提取更多内容。您可以多次使用同一个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;
}