版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/leolewin/article/details/51078870
如题,在面试和实际应用中,经常会碰到一个场景:读入以指定符号间隔的一组数据,放入数组当中。
看了不少博客,总结了一个个人目前觉得比较简便的方法(其实和java比也一点不简便。。。。)
基本思路就是:将输入的数据读到string中,然后将string中的间隔符号用空格代替后,输入到stringstream流中,然后输入到指定的文件和数组中去
具体代码如下:
// cin,.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include <string>
#include <sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string strTemp;
int array[4];
int i = 0;
stringstream sStream;
cin >> strTemp;
int pos = strTemp.find(',');
while (pos != string::npos)
{
strTemp = strTemp.replace(pos, 1, 1, ' '); //将字符串中的','用空格代替
pos = strTemp.find(',');
}
sStream << strTemp; //将字符串导入的流中
while (sStream)
{
sStream >> array[i++];
}
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
return 0;
}
以上思路仅供参考,如果有更好的方案,欢迎提出和探讨。