Search code examples
c++istringstream

c++ istringstream() function converting string to int raises error


I have a string of digits. I am trying to print it as an int type each single digit in the string using istringstream. It works fine if pass whole string as argument to conversion function in main but if I pass it by index, it raises error.

How to make this code work using index to print each single digit in string array as an int.

Here is my code.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int strToNum(string str)
{
    istringstream ss(str);
    int n;
    ss>>n;
    cout<<n;
}

int main()
{
string str = "123";
for(int i=0; i<str.length(); i++)
//strToNum(str);  Works fine
strToNum(str[i]); //raises error
}

Solution

  • Others have explained your error. This is how you could make it work:

    strToNum( std::string(1, str[i]) );
    

    But I'd do this instead:

    for(int i=0; i<str.length(); i++)
        cout << str[i] - '0';
    

    But ask yourself if you really need this. Are you interested in the value or the representation? If the latter, just print chars.