enterprize
enterprize

Reputation: 1179

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
}

Upvotes: 0

Views: 3920

Answers (5)

alwaystudent
alwaystudent

Reputation: 181

Actually I use a template function to perform this task, which is a more useful way to write the function that originated this thread ( because this single function can convert a string to any type of number: int, float, double, long double ):

#include "stdafx.h"
#include <string>
#include <iostream>
#include <Windows.h>
#include <sstream>
#include <iomanip> 
using namespace std;

template <typename T>
inline bool StrToNum(const std::string& sString, T &tX)
{
    std::istringstream iStream(sString);
    return (iStream >> tX) ? true : false;
}


void main()
{
    string a="1.23456789";
    double b;
    bool done = StrToNum(a,b);
    cout << a << endl;
    cout << setprecision(10) << b << endl;

    system ("pause");
}

setprecision(10) ( iomanip ) is required otherwise istringstream will hide some decimals

Upvotes: 0

inkooboo
inkooboo

Reputation: 2944

You don't need istringstream at all.

int strToNum(char ch)
{
    cout << ch;
}

Upvotes: 1

P0W
P0W

Reputation: 47784

It raises error because str[i] is a char

however , strToNum(string str) excepts a string

Try this :

for(int i=0; i<str.length(); i++)
  strToNum(string(1,str[i])); //Convert char to string

See here

Upvotes: 4

jrok
jrok

Reputation: 55395

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.

Upvotes: 2

Marcin Łoś
Marcin Łoś

Reputation: 3246

str[i] is a char, while the strToNum expects a string, hence the type error.

Upvotes: 5

Related Questions