1.1 输入输出
cin/cout scanf/printf
- 万能头文件 #include<bits/stdc++.h>
cin/cout 速度相对慢,需要关同步,代码如下
#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;
cout<<y<<endl<<x;
return 0;
}
scanf/printf 速度更快,但需要控制输入输出格式:
- %s 字符串
- %c 字符
- %lf 双精度浮点数(doule)
- %lld 长整型(long long)
- %llu 无符号长整形(unsigned long long),不能读入负数
1.2 多组输入
1.2.1 有条件多组输入:
//统计偶数个数及奇数和
#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;
return 0;
}
1.2.2 无条件多组输入:
//统计偶数个数及奇数和
#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;
//ctrl+z退出循环
}
cout<< num_even << endl<<sum_odd;
return 0;
}
1.2.3 getline读入带空格的字符串:
- 我们在读入字符串的时候如果用 cin 或 scanf 会无法读入空格,因为 cin 或 scanf 读入空格后会认为字符串读入已经结束。所以我们需要用 getline 读入带空格的字符串。
//利用 getline 读入空格,利用字符串的 size() 函数求出字符串长度,for循环遍历非空格的字符
//测试数据 Love makes the world go around
//结果 25
#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;
return 0;
}
-
一个英语句子,单词中间有许多个连续空格。现在请你编程帮他过滤掉单词中间的多余的空格,只留下一个空格。
-
输入:一行,一个字符串(长度不超过200),句子的头和尾都没有空格
//方法1:利用 getline ,输入整个字符串,只要不是连续出现的空格或者非空格字符,就输出
//测试用例:Hello world. This is c++ language.
//输出:Hello world. This is c++ language.
#include<bits/stdc++.h>
using namespace std;
int main(){
string str;
getline(cin,str);
int n=str.length();
for(int i=0;i<n;i++){
if((str[i]==' ' && str[i+1]!=' ')||str[i] !=' '){
cout<<str[i];
}
}
return 0;
}
//方法2:利用 cin 不能读入空格的特性,结合 while 循环读入,可以巧妙忽略空格。
#include<bits/stdc++.h>
using namespace std;
int main(){
string str;
while(cin>>str){
cout<<str<<" ";
}
return 0;
}
- getline与cin混用产生的问题及字符串与数字的转换 简单来讲就是 cin 会剩一个换行符, getline 会把这个换行符读进来导致 直接结束字符串读入。 所以说我们在使用的时候,尽量避免 getline 与 cin 混用。
//输入:第一行一个整数 n,表示字符串长度(包含空格在内),第二行一个字符串 s
//测试用例:
//30
//Love makes the world go around
//输出:输出文件只有一行,包含一个整数,即作文标题的字符数(不含空格和换行符)。
//输出:25
#include<bits/stdc++.h>
using namespace std;
int main(){
string t;
string s;
getline(cin,t);
getline(cin,s);
int n = stoi(t);//将字符串转化为数字
int cnt=0;
for(int i=0;i<n;i++){
if(s[i]!=' '){
cnt++;
}
}
cout<<cnt<<endl;
return 0;
}
- stoi 函数将字符串转化为了数字
- to_string() 将数字转化为字符串
1.3 日期模板
#include<bits/stdc++.h>
using namespace std;
int main(){
for(int year=2000;year<=2022;year++)
for(int month=1;month<=12;month++)
for(int day=1;day<=31;day++)
{
if(month == 1 || month == 3 || month == 5 || month == 7 ||
month == 8 || month == 10 || month == 12);
else if(month == 2)
{
if((year%4==0&&year%100!=0) || year % 400 == 0)
{
if(day > 29) break;
}
else
{
if(day > 28) break;
}
}
else
{
if(day > 30) break;
}
}
return 0;
}