Question

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
}
Était-ce utile?

La solution 3

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.

Autres conseils

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

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

You don't need istringstream at all.

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

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top