21

A String is given as an input which consists of numbers and I want to convert it into integer arrays in C++.

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

using std::string;
using std::stringstream;
using std::cout;
using std::endl;

int main(int argc,char** argv) {

    string num="-24 2 90 24 50 76";

    stringstream stream(num);

    while(stream){
        int n;
        stream>>n;
        cout<<n<<endl;
    }

    return 0;
}

Output(GCC) :

-24 2 90 24 50 76 76

Why am i getting extra value and what is the efficient to convert them into integer array ?

UPDATE:

What if the string stream contains delimiter other than space, How to parse this? For eg: string num="-24,2,90,24,50,76";

1
  • No, storing in a vector is a good way to get them into something that for all intents and purposes is in array. Commented Jul 18, 2013 at 13:40

3 Answers 3

22

The end of file condition is not set upon a succesful parse, you have to check the state of the stream after parsing.

The second 76 is basically just pure chance. An unsuccesful parse leaves the target operand untouched, and because you did not initialize n, it can be anything.

A quickfix:

stream>>n;
if (stream)
    cout<<n<<endl;

A cleaner fix:

int n;
while(stream >> n){
    cout<<n<<endl;
}

To store those integers, the canonical way is to use std::vector if the number of elements is unknown. An example usage:

std::vector<int> values;
int n;
while(stream >> n){
    ...do something with n...
    values.push_back(n);
}

However, you can use iterators over streams and use the following:

// Use std::vector's range constructor
std::vector<int> values(
     (std::istream_iterator<int>(stream)), // begin
     (std::istream_iterator<int>()));      // end
8
  • 1
    Actually, the value isn't undefined; for the numeric input conversions, the standard guarantees that the target will not be modified if there is an error. So he's guaranteed to see the last value read. Commented Jul 18, 2013 at 13:52
  • And the important point is that he's using the value without having checked that the input succeeded. (This is implicit in your code, but it's worth saying explicitly.) Commented Jul 18, 2013 at 13:53
  • 3
    And finally, if you want a vector of int, the canonical way is: std::vector<int> values( (std::istream_iterator<int>( stream )), (std::istream_iterator<int>()) );. No loops, no push_back; everything happens in the constructor. Commented Jul 18, 2013 at 13:55
  • 2
    @JamesKanze: But it is undefined because n was not initialized; I elaborated a bit on that. Good second third point, glad you reviewed my answer. Commented Jul 18, 2013 at 14:12
  • Ah, yes. Because he defines a new n each time around. I was thinking of something along the lines of int n; while ( !stream.eof() ) (which we see so often). Commented Jul 18, 2013 at 14:21
6

Another means of dealing with a character separated integers list using a vector, which is even perhaps a little more simplistic is more like this:

string str = "50,2,25,38,9,16";
vector<int> ints;
stringstream ss(str);
int n;
char ch;

while(ss >> n) {
    if(ss >> ch)
        ints.push_back(n);
    else
        ints.push_back(n);
}

that way you can move past any character separations (if they exist) first and then default back to grabbing the integers and adding them to the list if they don't (AKA the end of the list)

1
  • What is with that inner if statement? It's doing the same no matter what?
    – Managarm
    Commented Mar 13, 2023 at 16:51
2

i don't know if you find the answer for your updated question or not. if you don't you can easily do it by the code

for (string::iterator it = num.begin(); it != num.end(); ++it) {
    if (*it == ',') {
        *it = ' ';
    }
    else continue;
}

this code removes all your colons and replaces them by space. then you can do just normally

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.