场景:
输入一行整数:
1 2 -3 456 0
在笔试题中,经常需要输入一行整数保存到数组中(整数之间用空格隔开),例如上面一行数需要保存到整数数组a[]
中,即a[0]=1, a[1]=2, a[2]=-3, a[3]=456, a[4]=0
。
解决办法一
输入操作符cin>>
在输入时,默认是以空格符或换行符表示输入结束。这里使用getchar()
函数解决空格符带来的输入问题。
#include <iostream>
#include <vector>
using namespace std;
int main(){
//1.定义一个整数数组,vector可以不用初始化大小,并且能够根据需要自动扩容
vector<int> v;
//2.初始化一个int整数
int n;
cout << "输入:" << endl;
//3.只要不换行就一直保存
do
{
cin >> n;
v.push_back(n);
} (while(getchar() != '\n')
//4.遍历数组
cout << "遍历:" << endl;
for(vector<int>::iterator it = v.begin(); it != v.end(); it++){
cout << *it <<endl;
}
return 0;
}
解决办法二
使用istringstream
型对象,其包含在头文件sstream
中。
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
string s = "1 2 -3 456 0";
vector<int> v;
istringstream is(s);
string buf;
while(getline(is, buf, ' ')) // 如果字符串s中使用的是逗号隔开,这里就替换' ' 为 ','
{
v.push_back(stoi(buf)); // stoi()可将string型数据转换为int型
}
for(auto i:v)
{
cout<<i<<" ";
}
return 0;
}
总结
- 本质上,在这里使用vector数组保存用空格隔开的多个字符(负数在这里被视为一个字符)
- 本篇是将输入的带空格字符串转整形数组,此外可推广至转化为字符数组