PAT (Basic Level) Practice 1009 说反话(getchar的应用理解)

乙级1009

在这里插入图片描述

用java的split()更轻松,这次用C写的话,C没有字符串数组,就建一个结构体来存储吧,这样输出就方便许多了。
感觉题目的重点是“什么时候进行输出”,这样就应该考虑“如何判断回车键”,查了下资料,发现getchar()这个函数可以使用,介绍一下getchar()的用法:

以下介绍来自百度百科:

#include<stdio.h>
#include<conio.h>
main(void)
{
    int c;
    int a;
    a=getchar();
     
    if (EOF!=a)
        printf("%c",a);
         
    while((c=getchar())!='\n')//c接收的值是输入第一个字符后按下的回车换行符'\n',c是不会显示的
    {
        if (EOF==a)
            break;
        printf("%d",c);
    }
    getchar();
}
/*getchar()-Note that getchar reads from stdin and is line buffered; 
this means it will not return until you press ENTER. */

用我自己的方法解释就是说getchar会读取你上一次输入的东西是什么,并且返回读取到的这个东西的值

代码实现:

#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
struct sentence{
	char vol[100];
};
int main(){
	sentence sen[100];
	int i = 0,cal = 0;
	int c;
	while(scanf("%s",&sen[i].vol)!=EOF){
		i++;
		cal++;
		if((c=getchar())=='\n'){
			break;
		}
	}
	i--;cal--;
	int isfirst = 1;
	for(int i = cal;i>=0;i--){
		if(isfirst){
			cout<<sen[i].vol;
			isfirst = 0;
		}else{
			cout<<' '<<sen[i].vol;
		}
		
	}
}

猜你喜欢

转载自blog.csdn.net/a656418zz/article/details/83154601