Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth character of string to int

Tags:

c++

How can I convert nth character of string to number? I have a long number expressed as string and I'd like to make an array of it, where each character would be seperate number. I've tried with followed piece of code:

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

int main()
{
    string str ="73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018";
    int ints[1000] = {0};

    for (int i = 0; i < str.size(); i++)
    {
        istringstream ss(str[i]);
        ss >> ints[i];
    }

    cout << ints[9] << endl;

    return 0;
}

But it doesn't work.

like image 303
user1626154 Avatar asked Aug 26 '12 18:08

user1626154


1 Answers

How about:

for (int i = 0; i < str.size(); i++)
    if (isdigit(str[i]))
        ints[i] = str[i] - '0';

Or maybe:

for (string::const_iterator it = str.begin();
     it != str.end(); it++)
         if (isdigit(*it))
             ints[i] = *it - '0';
like image 83
cnicutar Avatar answered Oct 01 '22 14:10

cnicutar