笔试题中往往会给一个数组,但是数组的输入方式确实如下:
1,4,12,3,9,6
那么只能用string来获取输入的数组,在用时必须要进行分割,取出自己需要的数组元素,解决方法如下:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string str;
int arr[100]; //不确定输入数组元素的具体个数,先开100个
stringstream sStream;
cin >> str;
int pos = str.find(',');
while (pos != -1)
{
str = str.replace(pos, 1, 1, ' '); //替换','
pos = str.find(',');
}
sStream << str; //将字符串导入流中
int i = 0;
while (sStream)
sStream >> arr[i++];
for (int j = 0; j < i - 1; j++)
cout << arr[j] << " ";
cout << endl;
return 0;
}