I'm having trouble converting a string to an array of ints
(assuming the string is less than 10 characters)
I cannot understand why this is failing
thanks for any assistance!
1 2 3 4 5 6 7 8 9 10
|
string s;
cin >> s;
int array[10];
for(int i=10, j =s.length(); i>0 && j>0; i--,j--){
array[i]=(int)s[i];
}
for(int b=10; b>0;b--){
cout << array[b];
}
|
Last edited on
Looks like the problem is line 5.
You can't just cast a char to int. '1' is not 1.
I'll show you a similar example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
#include <vector>
int main(void)
{
std::string s;
std::cin >> s;
std::vector<int> array;
for (int i = 0; i < (int)s.length(); i++)
array.push_back(s[i] - '0');
for (int i = 0; i < (int)array.size(); i++)
std::cout << array[i];
return 0;
}
|
If you look at line 11, I subtract s[i] with '0', and that will produce corresponding digit. (assuming entered text are all digits).
thank you!
Topic archived. No new replies allowed.