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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With