输入输出练习

更多内容

输入一个矩阵,给定n行,但是每行的个数不一样

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <typeinfo>

using namespace std;
int main() {
	string input;
	vector<vector<int>> ans;
	for (int i = 0; i < 3; i++) {
		getline(cin, input);
		stringstream s(input);
		string temp;
		vector<int> p;
		while (getline(s,temp,' ')) {
			p.push_back(stoi(temp));
		}
		ans.push_back(p);
		p.clear();

		
	}
	cout << "kj" << endl;

	for (auto p : ans) {
		for (auto q : p) {
			cout << q << ' ';
		}
		cout << endl;
	}
	cout << endl;
}

如果需要规定矩阵的行数列数

	int n, m;
	string input;
	getline(cin, input);
	stringstream s1(input);
	s1 >> n >> m;

此时可以共用一个stringstream,但是每次用之前需要清空

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <typeinfo>

using namespace std;
template <typename T>

void matirxdisplay(T m) {
	for (auto p : m) {
		for (auto q : p) {
			cout << q << ' ';
		}
		cout << endl;
	}
}
int main() {
	int n, m;
	string input;
	getline(cin, input);
	stringstream ss(input); //定义一个共用的stringstream
	ss >> n >> m;
	vector<int> p;
	vector<vector<int>> ans;

	for (int i = 0; i < n; i++) {
			getline(cin, input);
			ss.clear(); //清空操作
			ss.str(input);
			string temp;
			while (getline(ss, temp, ' ')) {
				p.push_back(stoi(temp));
			}
			ans.push_back(p);
			p.clear();
		
	}
	matirxdisplay(ans);
}

输入一个字符串,输出一个字符串

能够自动跳过空格,找到子字符串
比如输入a bb cc dddd d ss
可以得到

bb 
cc 
dddd 
d 
ss

即能够自动分割空格

#include <iostream>
#include <string>
#include <sstream>

using namespace std;
int main() {
	string input;
	getline(cin,input);
	stringstream s(input);
	string temp;
	while(s >> temp){
		cout << temp << endl;
	}
}

输入是1,23,4;3,4;1;23,1,2;的形式来构造矩阵
先利用;将每行截断,再在每行里用,将各元素截断

int main() {
	vector<vector<int>>ans;
	vector<int> line;
	string input;
	getline(cin,input);
	stringstream s1(input);

	string temp1;
	while(getline(s1,temp1,';')){
		stringstream s2(temp1);
		string temp2;
		while(getline(s2,temp2,',')){
			line.push_back(stoi(temp2));
		}
		ans.push_back(line);
		line.clear();
	}
	matirxdisplay(ans);
	return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值