蓝桥杯历年省赛真题
点击链接免费加入题单
输入输出
cin/cout与scanf/printf
-
万能头文件
#include<bits/stdc++.h>
-
cin
与cout
是 C++ 提供的函数输入输出方便但速度较慢,所以需要用指令进行输入输出加速,切记使用加速命令后不要同时使用cin/cout与scanf/printf
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int x, y; // 声明变量
cin >> x >> y; // 读入 x 和 y
cout << y << endl << x; // 输出 y,换行,再输出 x
return 0; // 结束主函数
}
scanf
与printf
其实是 C 语言提供的函数。大多数情况下,它们的速度比cin
和cout
更快,并且能够控制输入输出格式。
%s
表示字符串。%c
表示字符。%lf
表示双精度浮点数 (double
)。%lld
表示长整型 (long long
)。%llu
表示无符号长整型 (unsigned long long
),无符号整数不能读入负数。
多组输入
我们在输入输出的时候要遵守题目的输入输出格式规范常见的有以下几种输入方式
有条件的多组输入
奇偶统计
- 题目描述
给你若干个数字,最后一个数字是 0 0 0,让你统计这些数字中有有多少个偶数,和所有奇数的和。
- 输入格式
一行,若干个数字,最后一个数字是 0 0 0
- 输出格式
第一行是这些数字中的偶数的个数
第二行是这些数字中奇数的总和
- 样例
输入
12 53 72 3 9 94 36 54 28 99 93 36 6 0
输出
8
257
- 题目思路与代码
利用while循环加if分支语句进行判断当输入的数字为 0
的时候break跳出循环
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,num_even = 0,sum_odd = 0;
while(cin >> n)
{
if(n == 0) break;//0的时候结束循环
else
{
if(n % 2 == 0) num_even++;
else sum_odd += n;
}
}
cout << num_even << endl << sum_odd;
}
无条件的多组输入
奇偶统计改
题目同上,删去了以 0
作为循环结束的条件
- 题目思路与代码
利用while循环进行读入,但输入的时候你可能发现程序无法退出,这时候需要输入 ctrl
+ z
再按下回车就可以正常结束程序。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,num_even = 0,sum_odd = 0;
while(cin >> n)
{
if(n % 2 == 0) num_even++;
else sum_odd += n;
}
cout << num_even << endl << sum_odd;
}
getline读入带空格的字符串
我们在读入字符串的时候如果用 cin
或 scanf
会无法读入空格,因为 cin
或 scanf
读入空格后会认为字符串读入已经结束。所以我们需要用 getline
读入带空格的字符串。
作文标题
- 题目思路
利用 getline
读入空格,利用字符串的 size()
函数求出字符串长度,for循环遍历非空格的字符
- 代码
#include<bits/stdc++.h>
using namespace std;
int main() {
string str;
getline(cin,str);
int cnt = 0;
int n = str.length();
for(int i = 0;i < n;i++) {
if(str[i] != ' ') {
cnt++;
}
}
cout << cnt << endl;
}
- 但有的时候我们也可以利用
cin
与scanf
根据空格判定字符串读入结束的特性方便地解决一些问题
拓拓在打字
解法1
- 题目思路
利用 getline
,输入整个字符串,然后只要不是连续出现的空格或者非空格字符,就输出
- 代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
for(int i = 0;i < s.size();i++)
{
if((s[i] == ' ' && s[i+1] != ' ') || s[i] != ' ')
cout<<s[i];
}
}
解法2
- 题目思路
利用 cin
不能读入空格的特性,结合 while
循环读入,可以巧妙忽略空格。
- 代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
while(cin >> str) {
cout << str << " ";
}
}
getline与cin混用产生的问题及字符串与数字的转换
简单来讲就是 cin
会剩一个换行符,getline
会把这个换行符读进来导致直接结束字符串读入。
所以说我们在使用的时候,尽量避免 getline
与 cin
混用。
作文标题改
#include<bits/stdc++.h>
using namespace std;
int main() {
string t;
string str;
getline(cin, t);
getline(cin,str);
int cnt = 0;
int n = stoi(t);//将字符串转化为数字
for(int i = 0;i < n;i++) {
if(str[i] != ' ') {
cnt++;
}
}
cout << cnt << endl;
}
在上面的代码中我们注意到我们使用了 stoi
函数将字符串转化为了数字,如果想将数字转化为字符串可以使用 to_string()
指令
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
string t;
cin >> n;
t = to_string(n);
cout << t << endl;
}