C++输入输出的一些问题
在之前的文章中我们讨论过各种数据类型使用printf输出时,格式化字符串的使用方法。
下面我们来讨论一些其他的输入输出技巧。
scanf读入特定格式的数据
scanf可以读如特定格式的数比方说2:3,可以写成scanf("%d:3%d",&a,&b);
这样的技巧可以很方便的解决(2018蓝桥杯P4)[https://www.lanqiao.cn/problems/175/learning/\]
cpp
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
int T;
const int N=30;
string s;
int main(){
cin>>T;
while (T--){
int t1;
int b11,b12,b13,b21,b22,b23;
int e11,e12,e13,e21,e22,e23;
scanf("%d:%d:%d",&b11,&b12,&b13);
scanf("%d:%d:%d",&b21,&b22,&b23);
char input;
t1=b11*3600+b12*60+b13-(b21*3600+b22*60+b23);
while (input=getchar(),input!='\n'){
if (1<=input-'0'&&input-'0'<=9){
t1+=(input-'0')*24*3600;
}
}
scanf("%d:%d:%d",&b11,&b12,&b13);
scanf("%d:%d:%d",&b21,&b22,&b23);
int t2;
t2=b11*3600+b12*60+b13-(b21*3600+b22*60+b23);
while (input=getchar(),input!='\n'){
if (1<=input-'0'&&input-'0'<=9){
t2+=(input-'0')*24*3600;
}
}
int ans=(t1+t2)/2;
if (ans<0)
ans=-ans;
int h=ans/3600;
ans-=h*3600;
int m=ans/60;
ans-=m*60;
printf("%02d:%02d:%02d\n",h,m,ans);
}
return 0;
}
读入一整行数据
通过笔者进行蓝桥2018P4求解时候的实验,笔者发现直接使用getline()进行数据读取,如果和scanf()进行混合使用就会出现问题。
经过资料查阅,笔者发现了如下的问题:
scanf 读取数据时(比如 %d、%s、%f 等格式),会跳过开头的空白字符(空格、制表符、换行符),但读取完目标数据后,不会清空输入缓冲区中紧随其后的换行符(\n)。
getline(C++ 中的 std::getline 或 C 中的 getline)的逻辑是:从缓冲区读取字符,直到遇到换行符 \n 为止,并且会把这个换行符从缓冲区中移除(但不包含在最终读取的字符串中)。
因此,若getline和scanf混用就会导致缓冲区中换行符的读取出现问题。
这时我们可以避免使用scanf,所有数据读取全部使用getline()
或者我们保留scanf的写法,利用getchar()手动实现读取一行的操作
cpp
char input;
while (input=getchar(),input!='\n'){
...
}