OJ的自我修养:C++输入输出总结

1. 字符串

1.1 字符串的输入

1.1.1 输入一个字符串

#include <string>
#include<iostream>

using namespace std;

int main()
{
  string str;
  cin>>str;//cin遇到空格结束读取
  cout<<str<<endl;

  getline(cin,str);//使用getline函数可以获取包含空格的字符,以回车键结束
  cout<<str<<endl;
  return 0;
}

1.1.2 输入多个字符串

#include <string>
#include<iostream>

using namespace std;

int main()
{
  string str;
  while(getline(cin,str)){//遇到EOF/CTRL+Z则退出
    cout<<str<<endl;
  }

  return 0;
}

2. 数组

2.1 数组的输入

2.1.1 输入一个定长一维数组

#include<iostream>
using namespace std;

int main() {
	const int N = 5;
	int A[N] = { 0 };
	for (int i = 0; i < N; i++) {
		cin >> A[i];
	}

	return 0;
}

2.1.2 输入一个不定长一维数组

#include<iostream>
#include<vector>
using namespace std;

int main() {
	vector<int>num;
	int value;
	while (cin >> value)//忽略空格,回车,Tab,遇到EOF会跳出循环
		num.push_back(value);

	return 0;
}

2.1.3 输入一个行数确定列数不确定的矩阵

#include<iostream>
#include<vector>
using namespace std;
const int N = 3;//行数是确定的
int main() {
	vector<vector<int>>num(N);
	int value;
	for (int i = 0; i < N; i++) {
		while (cin >> value) {
			num[i].push_back(value);
			if (getchar() == '\n')//遇到回车结束
				break;
		}
	}
	/*输出不定长数组*/
	for (int i = 0; i < N; i++) {
		vector<int>::iterator it;//使用迭代器输出不定长的vector
		for (it = num[i].begin(); it != num[i].end(); it++)
			cout << *it << "\t";
		cout << endl;
	}
	
	return 0;
}

2.1.4 输入一个行数不确定列数确定的矩阵

#include<iostream>
#include<vector>
using namespace std;

int main()
{
	int a,b;
    vector<vector<int>> vc;

	while(cin >> a >> b)//cin遇到EOF/Ctrl+Z 或者非法字符就能退出循环
	{
	    vector<int> tmp;
	    tmp.push_back(a);
	    tmp.push_back(b);
	    vc.push_back(tmp);
	}
	return 0;
}

2.1.5 输入一个二维不定长的矩阵

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

using namespace std;
string line,num;
size_t linenum = 0;
vector<vector<int>> v;

int main()
{
  while(getline(cin,line)){
    istringstream iss(line);//读取字符串
    while(line>>num){//依次获取每行中字符串
        v.push_back(vector<int>());//插入一个一维vector
        v[linenum].push_back((stoi(num)));//把数依次存到一行数组中,使用stoi将字符串转为int
    }
    ++linenum;//新增一行
  }
  return 0;
}

3. 格式化输入输出

#include<iostream>
using namespace std;

int main() {
	float a;
	char c;
	/*C++支持C类型的格式化输入输出*/
	scanf_s("%f%*c%c", &a, &c);//%*c为忽略任意字符
	printf("%5.2f\t%c", a,c);//格式化输出
	return 0;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值