我正在练习用户输入处理。我的目标是让用户输入一行由空格(“”)分隔的整数,将它们作为整数读取,存储它们并稍后处理它们。我偶然发现了一个有趣的问题(至少在我看来),我这样做的方式似乎总是没有读取用户输入的最后一个数字。我将在此处发布整个程序(因为其中包含一些额外的库)。我在程序中留下了一些评论
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;
int main()
{
//this vector will store the integers
vector<int> a;
// this will store the user input
string inp;
getline(cin, inp);
// this string will temporarily store the digits
string tmp;
//be sure that the reading part is okay
cout << inp << endl;
//until you meet something different than a digit, read char by char and add to string
for(int i = 0; i < inp.length(); i++)
{
if(isdigit(inp[i]))
{
tmp +=inp[i];
}
else
{
// when it is not a character, turn to integer, empty string
int value = atoi(tmp.c_str());
a.push_back(value);
tmp = "";
}
}
// paste the entire vector of integers
for(int i = 0; i < a.size(); i++)
{
cout << a[i] << endl;
}
return 0;
}