hdu 1062 Text Reverse

来源:互联网 发布:韩国三角饭团淘宝 编辑:程序博客网 时间:2024/04/27 20:07
                Text Reverse

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7032 Accepted Submission(s): 1908

Problem Description
Ignatius likes to write words in reverse way. Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.

Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single line with several words. There will be at most 1000 characters in a line.

Output
For each test case, you should output the text which is processed.

Sample Input
3
olleh !dlrow
m’I morf .udh
I ekil .mca

Sample Output
hello world!
I’m from hdu.
I like acm.

Hint

Remember to use getchar() to read ‘\n’ after the interger T, then you may use gets() to read a line and process it.

题意:输入一个字符串,将字符串中的 单词反转后输出,一次反转一个。

做这道题目以前,我打算先写一下getchar();
百科百科:
getchar 由宏实现:#define getchar() getc(stdin)。getchar有一个int型的返回值.当程序调用getchar时.程序就等着用户按键.用户输入的字符被存放在键盘缓冲区中.直到用户按回车为止(回车字符也放在缓冲区中).当用户键入回车之后,getchar才开始从stdio流中每次读入一个字符.getchar函数的返回值是用户输入的字符的ASCII码,如出错返回-1,且将用户输入的字符回显到屏幕.如用户在按回车之前输入了不止一个字符,其他字符会保留在键盘缓存区中,等待后续getchar调用读取.也就是说,后续的getchar调用不会等待用户按键,而直接读取缓冲区中的字符,直到缓冲区中的字符读完为后,才等待用户按键.

#include<stdio.h>int main(){    char c1,c2;    c1=getchar(),c2=getchar();    //putchar(c1);    //putchar(c2);    printf("%c %c\n",c1,c2);    return 0;}

这里顺带介绍一下gets()函数
gets从标准输入设备读字符串函数。可以无限读取,不会判断上限,以回车结束读取,所以程序员应该确保buffer的空间足够大,以便在执行读操作时不发生溢出。
例子:

#include <stdio.h>    //这个头文件包含gets()函数,这个函数在ISO/IEC 9899 2011(C11)标准中被移除int main(void){    char str1[5];  //不要char*p,然后gets(p),这是错误的,因为p没有指向有效的内存,它可能指向任何                   //     地方的未知大小的内存块,这样以来,就可能修改了不属于本程序的内存的内容    gets(str1);    printf("%s\n", str1);    return 0;}

………………分割线………………
c语言版的答案如下

#include<stdio.h>#include<string.h>int main(){    char str0[1000],str1[100];    int length,T,t,i,j,k;    scanf("%d",&T);    getchar();    while(T--){        gets(str0);        length=strlen(str0);        for(i=0,j=0,t=0;i<length;i++){            if(str0[i]!=' ')            str1[j++]=str0[i];            else{                if(t!=0)                printf(" ");                for(k=j-1;k>=0;k--){                    printf("%c",str1[k]);                }                t=1;                j=0;            }            if(i==length-1){                printf(" ");                for(k=j-1;k>=0;k--){                    printf("%c",str1[k]);                }            }        }        printf("\n");    }    return 0;} 
0 0
原创粉丝点击