Stringstream when iterating through string doesnt work

user3651193 picture user3651193 · Oct 12, 2015 · Viewed 11.9k times · Source

So i want to use string stream to convert strings to integers.

assume everything is done with:

 using namespace std;

a basic case that seems to work is when I do this:

 string str = "12345";
 istringstream ss(str);
 int i;
 ss >> i;

that works fine.

However lets say I have a string defined as:

string test = "1234567891";

and I do:

int iterate = 0;
while (iterate):
    istringstream ss(test[iterate]);
    int i;
    ss >> i;
    i++;

this doesnt work as i want. essentially I was to idividually work on each element of the string as if it is a number, so i want to convert it to an int first, but i cant seem too. Could someone please help me?

the error i get is:

   In file included from /usr/include/c++/4.8/iostream:40:0,
             from validate.cc:1:
/usr/include/c++/4.8/istream:872:5: note: template<class _CharT, class _Traits, class _Tp> std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&&, _Tp&)
 operator>>(basic_istream<_CharT, _Traits>&& __is, _Tp& __x)
 ^
/usr/include/c++/4.8/istream:872:5: note:   template argument     deduction/substitution failed:
validate.cc:39:12: note:   ‘std::ostream {aka std::basic_ostream<char>}’ is not derived from ‘std::basic_istream<_CharT, _Traits>’
cout >> i >> endl;

Answer

HadeS picture HadeS · Oct 12, 2015

There are two points you should understand.

  1. If you use indexes to access string, you will get characters.
  2. istringstream requires string as a parameter not characters to create object.

Now you in your code

    int iterate = 0;
     while (iterate):
    /* here you are trying to construct istringstream object using  
 which is the error you are getting*/
        istringstream ss(test[iterate]); 
        int i;
        ss >> i;

To correct this problem you can following approach

istringstream ss(str); 
int i;
while(ss>>i)
{
    std::cout<<i<<endl
}