Write a complete program that will correctly decode a set of characters into a valid message. Your program should read a given file of a simple coded set of characters and print the exact message that the characters contain. The code key for this simple coding is a one for one character substitution based upon a single arithmetic manipulation of the printable portion of the ASCII character set.
Input and Output
For example: with the input file that contains:
1JKJ‘pz‘{ol‘{yhklthyr‘vm‘{ol‘Jvu{yvs‘Kh{h‘Jvywvyh{pvu5 1PIT‘pz‘h‘{yhklthyr‘vm‘{ol‘Pu{lyuh{pvuhs‘I|zpulzz‘Thjopul‘Jvywvyh{pvu5 1KLJ‘pz‘{ol‘{yhklthyr‘vm‘{ol‘Kpnp{hs‘Lx|pwtlu{‘Jvywvyh{pvu5
your program should print the message:
*CDC is the trademark of the Control Data Corporation. *IBM is a trademark of the International Business Machine Corporation. *DEC is the trademark of the Digital Equipment Corporation.
Your program should accept all sets of characters that use the same encoding scheme and should print the actual message of each set of characters.
Sample Input
1JKJ‘pz‘{ol‘{yhklthyr‘vm‘{ol‘Jvu{yvs‘Kh{h‘Jvywvyh{pvu5 1PIT‘pz‘h‘{yhklthyr‘vm‘{ol‘Pu{lyuh{pvuhs‘I|zpulzz‘Thjopul‘Jvywvyh{pvu5 1KLJ‘pz‘{ol‘{yhklthyr‘vm‘{ol‘Kpnp{hs‘Lx|pwtlu{‘Jvywvyh{pvu5
Sample Output
*CDC is the trademark of the Control Data Corporation. *IBM is a trademark of the International Business Machine Corporation. *DEC is the trademark of the Digital Equipment Corporation.----------------------------------------------------------------------------------------------------------------------------题目解答:
#include<stdio.h> int main(){ char c; int j; while((c = getchar())!= EOF){ if(c != ‘\n‘){ putchar(c-7); } else putchar(c); } return 0; }
getchar()与scanf的作用是相同的,但就是比较简练。同理putchar().
谈下fgets(),这个函数是用来获取一行的。
#define LOCAL #include<stdio.h> #include<ctype.h> #include<string.h> #define MAXN 1000 char buf[MAXN]; int main(){ #ifdef LOCAL freopen("data.txt","r",stdin); freopen("out.txt","w",stdout); #endif int i,j; int tmp; while(fgets(buf,MAXN,stdin) != NULL){ tmp = strlen(buf); for(i = 0; i < tmp;i++){ j = toascii(buf[i])-7; printf("%c",j); } printf("\n"); } return 0; }
fgets(char* buf,int number,FILE *fin)从输入流里读入(number - 1)个字符转存到buf指向的地址中,遇到换行符‘\n‘或者文件结束符‘\0‘就会停止.
注意fgets的有效字符为(number - 1 )个,最后会加上文件结束符‘\0‘。fgets能读取有效的一行,因为它遇到回车符‘\n‘就会停止,而这个‘\n‘也会是buf中最后一个有效字符(再往后就是文件结束符‘\0‘).只有一种情况下,buf不会以‘\n‘为最后一个有效字符,那就是在遇到换行符之前遇到文件结束符‘\0‘,即输入文件本身不是以回车结束的。(引用于http://blog.sina.com.cn/s/blog_608e238e0100kvvi.html)。
使用fgets与题目不符,题目中输入没有说以换行符决定一行,所以还是用getchar比较合适。
2. 同时在提交时使用toascii来得到数字时,提示为WA。
#include <ctype.h>
定义函数:int toascii(int c);
函数说明:toascii()会将参数c 转换成7 位的unsigned char 值,第八位则会被清除,此字符即会被转成ASCII码字符。
返回值:将转换成功的ASCII 码字符值返回。
范例:将int 型a 转换成ASSII 码字符。
j = toascii(buf[i])-7;
使用这个的话,编译不能通过。若输入全是ascii码的话,由于ascii最大数字为127,第八位就是为0,不受影响。题目中说明输入为ascii码中的字符,因此,我认为这是平台的原因导致WA。