读取字符串中的数字
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
using namespace std;
int main()
{
string a;
getline(cin, a);
vector<int>digits;
int number = 0;
for (int i = 0; i < a.length(); i++)
{
if (isdigit(a[i]))
{
number *= 10;//如果还有后面数字,number乘10,让出个位
number += (a[i] - '0'); //数字字符的ascii - 字符'0'的ascii码就等于该数字.
if (i == a.size() - 1) digits.push_back(number);//没有这句话,如果结尾是数字,会读取不了
}
else if (a[i] != ' ')//不是数字不是空格,可以是字母和字符
{
if (i >= 1)
{
if (isdigit(a[i - 1]))
{
digits.push_back(number); number = 0;
}
}
}
}
for (int i = 0; i < digits.size(); i++)
{
cout << digits[i] << " ";
}
return 0;
}
例子:
输入:int arr[10]={1,2,3,4,5}
输出:10 1 2 3 4 5