ACM赛制的输入输出处理
输入cin
cin是C++中最常用的输入,用空格或者回车键分隔数据。
(分割符:enter,space)
- cin:去掉前面的分割符;遇到分割符停止;保留后面的分割符
- cin.get():读取一个任意字符(可以用来清分割符)
- cin.get(str):无法去掉前面的enter符;遇到enter符停止;最后一位是/0,即分隔符,不会往下继续传,保留在了字符数组里。接下来的输入流中的第一位不是分割符
- cin.get只能用于读取char数组,不能用来读取string,转换类型也不行。遇到enter符停止;保留后面的enter符。
cin.get(字符数组名,接收字符数目,遇到什么字符停止)
- cin.getline():一切和cin.get()相同,但是丢弃后面的enter符。也就是说cin.getline()执行完之后(就是输入流遇到了回车),它的最后一位也是/0,但是接下来的输入流中的第一位是分割符。刚才对cin.get()说的所有东西都对cin.getline()适用。
- getline可以用来读取string:getline(cin, str)
cin.get()和cin.getline()
cin.get()可以读取一个字符,可以用这个来吃掉一个分隔符。一般在读取一个字符串保存到字符数组中时,使用
比如:接受n长度的字符串,先输入n,在输入字符串
#include <iostream>
using namespace std;
int main() {
char s[100500];
int n=0;
cin >> n;
cin.get();
cin.get(s, n+1);
}
cin.get()作用是吸收掉cin>>n之后留下的分隔符,不然cin.get()直接接收到分隔符返回了
n+1是因为,cin.get()的第n+1位用于保存/0,所以要给这个/0留出一位
也可以加入第三个参数,遇到这个字符就停止输入了,但不包括这个字符
OJ平台常见输入输出处理
输入包括两个正整数a,b(1 <= a, b <= 10^9),输入数据包括多组。
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
while(cin>>a>>b)
{
cout<<a+b<<endl;
}
return 0;
}
输入包括数组个数
输入描述:
输入第一行包括一个数据组数t(1 <= t <= 100)
接下来每行包括两个正整数a,b(1 <= a, b <= 10^9)
#include<iostream>
using namespace std;
int main()
{
int t;
cin>>t;
int a,b;
while(t--)
{
cin>>a>>b;
cout<<a+b<<endl;
}
return 0;
}
计算a+b(有结束标志)
输入描述:
输入包括两个正整数a,b(1 <= a, b <= 10^9),输入数据有多组, 如果输入为0 0则结束输入
#include<bits/stdc++.h>
using namespace std;
int main(){
int a = 0, b = 0;
while(1){
cin >> a >> b;
if(!(a || b)) break;
cout << a + b << endl;
}
return 0;
}
计算一系列数的和(有结束标志)
输入描述:
输入数据包括多组。
每组数据一行,每行的第一个整数为整数的个数n(1 <= n <= 100), n为0的时候结束输入。
接下来n个正整数,即需要求和的每个正整数。
#include<bits/stdc++.h>
using namespace std;
int main(){
int input = 0, output = 0, N = 0;
while(1){
cin >> N;
if(N == 0) break;
output = 0;
while(N--){
cin >> input;
output += input;
}
cout << output << endl;
}
return 0;
}
计算一系列数的和
输入描述:
输入的第一行包括一个正整数t(1 <= t <= 100), 表示数据组数。
接下来t行, 每行一组数据。
每行的第一个整数为整数的个数n(1 <= n <= 100)。
接下来n个正整数, 即需要求和的每个正整数。
#include<bits/stdc++.h>
using namespace std;
int main(){
int N = 0, input = 0, output = 0, n = 0;
cin >> N;
while(N--){
cin >> n;
output = 0;
while(n--){
cin >> input;
output += input;
}
cout << output << endl;
}
return 0;
}
字符串输入处理
当读取字符串的时候需要注意,cin不能读取空白字符,比如空格,如果遇到空格则会直接终止字符串。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s; // 读到空白就结束当前的字符串
cout << s;
return 0;
}
如果要读取整行字符串,可以使用getline()和cin.getline()这两个函数,两个函数都是遇到定界符,则结束这行的字符串,定界符默认设置为回车。两个函数略有不同的是,getline()操作的对象是string,cin.getline()操作的对象的char数组。详细的定义如下:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
cout << s;
system("pause");
return 0;
}
输入多行字符串(行数未知)
string str;
vector<string> v;
while (getline(cin, str)) //读取输入的一行数据
{
if (str.size() == 0) break; //如果读取的是空,则读取结束
v.push_back(str);
}