我试图将字符串中的数字转换为int向量,但这会给我数字0到9的ASCII代码。
有没有办法只将数字转换为整数?我猜我必须使用char数组,因为atoi()不能与std :: string一起使用,而c_str()方法仅适用于整个字符串中的每个字符。
有没有办法只将数字转换为整数?我猜我必须使用char数组,因为atoi()不能与std :: string一起使用,而c_str()方法仅适用于整个字符串中的每个字符。
#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;
}
输出:
1 2 3 4 5 6 7 8 9 0
49 50 51 52 53 54 55 56 57 48
istringstream
能够实现你所需的功能吗?最好举个例子,提供输入和期望的输出。 - Nam Nguyenint(chars_and_numers[i])
并不像你想象中的那样工作。char
类型是一种整型,就像int
或short
一样。它保存了字符的(通常是)ASCII整数值,这就是为什么'0'
在你的数组中显示为48
。要将数字转换为其整数等效项,请使用chars_and_numbers[i] - '0'
,它从数字的ASCII值中减去了'0'
的整数值,得到'0'
的0
,'1'
的1
,以此类推。当然,对于这种特殊情况,您可能希望使用stringstream
,因此这并没有太大帮助,但至少可以教会您一些东西。 - Chris Lutzonly_numbers
看起来像{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }
还是{ 123, 456, 789, 0 }
? - Chris Lutz