cin和scanf判断读取输入结束

例子:
输入三个字符后,按各字符的ASCII码从小到大的顺序输出这三个字符。
Input
输入数据有多组,每组占一行,有三个字符组成,之间无空格。
Output
对于每组输入数据,输出一行,字符中间用一个空格分开。
Sample Input
qwe
asd
zxc
 
Sample Output
e q w
a d s
c x z

 

像上面的题目,输入包含多组数据但不确定为具体数值时,我们需要判断输入是否结束从而判断程序是否继续执行;
当使用scanf读取输入时,当输入文件结束时函数会返回EOF,EOF的值为-1;需要注意的是读取字符时,会把空格和回车都作为输入读取;
#include<iostream>
#include<vector>
#include<memory.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
int main(){
    char a,b,c,t;
    while(scanf("%c%c%c",&a,&b,&c)!=EOF){//这样数值之间不可以输入空格,应为空格也会被读取
                         //如果需要中间输入空格的话,可以scanf("%c %c %c",&a,&b,&c);
  getchar();//因为scanf会读取回车,所以通过getchar()把回车吸收掉
if(b<=c&&b<=a){ t=a; a=b; b=t; } else if(c<=a&&c<=b){ t=a; a=c; c=t; } if(c<b){ t=b; b=c; c=t; } cout<<a<<' '<<b<<' '<<c<<endl; } return 0; }

当使用cin输入时,可以直接while(cin>>a>>b>>c),因为主要没有读取结束标志,(cin>>a>>b>>c)就会返回true;当读取结束标志则返回false;
另外cin不会读取空格和回车;

#include<iostream>
#include<vector>
#include<memory.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
int main(){
    char a,b,c,t;
    while(cin>>a>>b>>c){
    if(b<=c&&b<=a){
        t=a;
        a=b;
        b=t;
    }
    else if(c<=a&&c<=b){
        t=a;
        a=c;
        c=t;
    }
    if(c<b){
        t=b;
        b=c;
        c=t;
    }
    cout<<a<<' '<<b<<' '<<c<<endl;
    }
    return 0;
}

在windows上输入EOF的方法为Ctrl+Z

其它平台上输入EOF的方法为Ctrl+D

posted on 2019-01-25 16:33  ggsdduzdl  阅读(1607)  评论(0编辑  收藏  举报

导航