使用C ++中的istringstream将字符串拆分为整数 [英] Splitting a string into integers using istringstream in C++

查看:382
本文介绍了使用C ++中的istringstream将字符串拆分为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 istringstream 将一个简单的字符串拆分为一系列整数:

  #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
pre>

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

解决方案

这是出来两次,因为你的循环是错误的, http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5\">http://www.parashift.com/c++-faq-lite/input-output.html# while(iss.eof())与没有区别。



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



p>

  #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;
}
}


I'm trying to use istringstream to split a simple string into a series of integers:

#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;
    } 
}

And i get:

* 1
* 2
* 3
* 3

Why is the last element always coming out twice? How to fix it?

解决方案

It's coming out twice because your looping is wrong, as explained (indirectly) at http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5 (while (iss) is not dissimilar from while (iss.eof()) in this scenario).

Specifically, on the third loop iteration, iss >> n succeeds and gets your 3, and leaves the stream in a good state. The loop then runs a fourth time due to this good state, and it's not until the next (fourth) iss >> n subsequently fails that the loop condition is broken. But before that fourth iteration ends, you still output n... a fourth time.

Try:

#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;
    } 
}

这篇关于使用C ++中的istringstream将字符串拆分为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆