您发布的内容以及 Jeremiah Willcock 使用 istringstream 的解决方案都有效。但是也可以考虑使用scanf 系列函数(对于几个整数来说并没有太大的区别,但对于更高级的输入,使用 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;
}