2011-03-02 107 views
14

我试图用istringstream一个简单的字符串分割成一系列整数使用istringstream整数:将字符串分割成C++

#include <string> 
#include <iostream> 
#include <sstream> 
#include <vector> 

using namespace std; 

int main(){ 

    string s = "1 2 3"; 
    istringstream iss(s); 

    while (iss) 
    { 
     int n; 
     iss >> n; 
     cout << "* " << n << endl; 
    } 
} 

,我也得到:

* 1 
* 2 
* 3 
* 3 

为什么最后一个元素总是出现两次?如何解决它?

回答

30

它出现了两次,因为你的循环是错误的,正如http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5while (iss)与本场景中的while (iss.eof())不相似)中所解释的那样。

具体而言,在第三次循环迭代中,iss >> n成功并获取您的3,并使流处于良好状态。由于这个良好的状态,循环第四次运行,直到下一个(第四个)iss >> n失败,循环条件被破坏。但在第四次迭代结束之前,您仍然会第四次输出n

尝试:

#include <string> 
#include <iostream> 
#include <sstream> 
#include <vector> 

using namespace std; 

int main() 
{ 
    string s = "1 2 3"; 
    istringstream iss(s); 
    int n; 

    while (iss >> n) { 
     cout << "* " << n << endl; 
    } 
} 
+0

我们该如何在for()循环中做到这一点? – 2014-01-12 09:31:07

+0

@SumitKandoi:你是什么意思?你为什么? – 2014-01-12 12:43:39

+0

实际上,我在while()循环中试过。我想我们可以在for()循环中做到这一点 – 2014-01-12 14:32:29

0

希望这有助于:
ISS:1 2 3
迭代1
ISS:1 2 3(最初)
n = 1的
ISS:2 3
// * 1打印
迭代2:
ISS:2 3(最初)
n = 2的
ISS:3
// * 2印刷
迭代3
ISS:3
n = 3个的
ISS: ''
迭代4
ISS: ''
N不改变//下垂设置EOF ISS的如从流
ISS没有进一步的输入:“”

而作为正确地通过上述讯息中提到,而(ISS)不是从而不同(iss.eof())。
在内部,函数(istream :: operator >>)首先构造一个sentry对象(将noskipws设置为false [这意味着空格是分隔符,列表将是1,2,3])来访问输入序列。然后(如果good [这里没有到达]),它调用num_get::get [获取下一个整数]来执行提取和解析操作,相应地调整流的内部状态标志。最后,它在返回之前销毁哨兵对象。

请参阅:http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/