C++带特殊符号的标准输入读取方法

近期秋招,做了不少的笔试,发现在使用C++语言按照题目要求读取数据时,由于操作不熟练,导致浪费了很多的时间。痛定思痛,决定总结一下该如何读取数据,以便下次参照使用。

要求:读入M行整数,行内相邻数据间用英文逗号“,” 隔开。例如

\begin{matrix} & & \\ & & \\ & & \end{matrix}\begin{matrix} 1,&1,&2 \\ 2,&3, &4 \\ 3, &4, &5 \end{matrix}

 代码如下:

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;


int main()
{
	int M;
	cin >> M;
	string strTmp;
	getline(cin, strTmp);

	vector<vector<int>>  vi;
	for (int ii = 0; ii < M; ++ii)
	{
		string str;
		getline(cin, str);
		
		int lastIdx = 0;
		vector<int> tmp;
		for (int jj = 0; jj != str.size()+1; ++jj)
		{
			if ((jj == str.size()) || str[jj] == ',')
			{
				stringstream stm;
				stm << str.substr(lastIdx, jj - lastIdx);
				int value;
				stm >> value;
				tmp.push_back(value);
				lastIdx = jj + 1;
			}
		}
		vi.push_back(tmp);
	}

	cout << endl;
	for (int ii = 0; ii < M; ++ii)
	{
		for (int jj = 0; jj < vi[ii].size()-1; ++jj)
		{
			cout << vi[ii][jj] << ",";
		}
		cout << vi[ii][vi[ii].size() - 1] << endl;
	}

	system("pause");
	return 0;
}

运行结果如下:

猜你喜欢

转载自blog.csdn.net/weixin_38984102/article/details/81638683
今日推荐