0

I am new to c++ programming. I have read how parsing can be done in SO questions using vector(Int tokenizer).But I have tried the following for array. I am able to parse only one number from string. If input string is "11 22 33 etc".

#include<iostream>
#include<iterator>
#include<vector>
#include<sstream>

using namespace std;

int main()
{

int i=0;
string s;
cout<<"enter the string of numbers \n";
cin>>s;
stringstream ss(s);
int j;
int a[10];
while(ss>>j)
{

    a[i]=j;
    i++;
}
for(int k=0;k<10;k++)
{
    cout<<"\t"<<a[k]<<endl;
}

}

If I give input as "11 22 33"

output

11
and some garbage values.

If i have initialized stringstream ss("11 22 33"); then its working fine. What am I doing wrong?

3 Answers 3

4

The problem is that:

cin>>s;

Reads one space separated word into s. So only 11 goes into s.

What you want is:

std::getline(std::cin, s);

Alternatively you can read numbers directly from std::cin

while(std::cin >> j) // Read a number from the standard input.
Sign up to request clarification or add additional context in comments.

Comments

0

It seems cin>>s stop at the first whitespace. Try this:

cout << "enter the string of numbers" << endl;
int j = -1;
vector<int> a;
while (cin>>j) a.push_back(j);

Comments

0

We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type variables

cin >> mystring;

However, as it has been said, cin extraction stops reading as soon as if finds any blank space character, so in this case we will be able to get just one word for each extraction.

From http://www.cplusplus.com/doc/tutorial/basic_io/

So you have to use getline()

string s;
cout<<"enter the string of numbers \n";
getline(cin, s);

Comments

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.