Reputation: 159
I'm trying to convert only the digits from a string to an int vector, but that gives me the ASCII codes for numbers 0 to 9 instead.
Is there any way to convert only the digits to integers? I guess I'll have to use a char array since atoi() don't work with std::string and the c_str() method don't work for every character, only the entire string.
#include <cctype>
#include <iostream>
#include <vector>
using namespace std;
int main() {
string chars_and_numbers = "123a456b789c0";
vector<int> only_numbers;
for (int i = 0; i < chars_and_numbers.length(); i++) {
if (isdigit(chars_and_numbers[i])) {
cout << chars_and_numbers[i] << " ";
only_numbers.push_back(int(chars_and_numbers[i]));
}
}
cout << endl;
for (vector<int>::iterator i = only_numbers.begin(); i != only_numbers.end(); i++) {
cout << *i << " ";
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 0
49 50 51 52 53 54 55 56 57 48
Upvotes: 3
Views: 2210
Reputation: 14505
ASCII Character ASCII Code(decimal) Literal Integer
'0' 48 0
... ... ...
'9' 57 9
int(chars_and_numbers[i])
returns you the underlying ASCII code of ASCII character instead of the literal integer what you want.
Generally, 'i' - '0'
results in i
if i
belongs to [0, 9].
E.g., '1' - '0'
returns you the distances between values of two ASCII characters(49 - 48), which is 1.
int main() {
string chars_and_numbers = "123a456b789c0";
vector<int> only_numbers;
for (int i = 0; i < chars_and_numbers.length(); i++) {
if (isdigit(chars_and_numbers[i])) {
cout << chars_and_numbers[i] << " ";
// here is what you want
only_numbers.push_back(chars_and_numbers[i] - '0');
}
}
cout << endl;
for (vector<int>::iterator i = only_numbers.begin(); i != only_numbers.end(); i++) {
cout << *i << " ";
}
return 0;
}
Upvotes: 4
Reputation: 2771
If your desired output when printing the vector of ints are the actual numbers 0 through 9, you can rely on the fact that the ASCII values for '0' through '9' are consecutive:
only_numbers.push_back(char_and_numbers[i] - '0');
Thus, '8' becomes '8' - '0', or 56 - 48, which is 8.
Upvotes: -1