Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

stl - Splitting a string into integers using istringstream in C++

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?

question from:https://stackoverflow.com/questions/65863310/how-to-store-multiple-long-numbers-from-a-string-into-a-vector

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...