本节书摘来自华章出版社《C语言解惑》一 书中的第2章,第2.7节,作者:刘振安 刘燕君,更多章节内容可以访问云栖社区“华章计算机”公众号查看。
【例2.9】下面的程序正确吗?
#include <stdio.h> void main() { char st[]="When you go home?"; printf("%s\n",st); //1 printf("%c\n",st[5]); //2 printf("%s\n",st[5]); //3 }【解答】编译能通过,但结果不正确。第1条输出语句中的st代表字符串的首地址,所以能输出字符串的内容。第2条语句的st[5]代表第6个元素y的地址,所以能正确输出“y”。第3条输出语句是错误的,因为%s是输出字符串,要求字符串“you go home?”的首地址。正确的写法是&st[5]。其实,可以简单地使用如下语句printf(&st[5]);将这种方法用到程序中。将其改写如下:
#include <stdio.h> void main() { char st[]="When you go home?"; printf("%s\n",st); printf(st); printf("\n"); printf("%c\n",st[5]); printf("%s\n",&st[5]); printf(&st[5]); printf("\n"); }可以对应下面的输出结果加深对字符串的理解。When you go home?When you go home?yyou go home?you go home?当定义字符串char c[]="abc";时,其实是由c[0]='a',c[1]='b',c[2]='c',c[3]='0'这4个元素组成。为它分配的长度要增加一位结束符。因此,定义时不能使用 char c[3]="abc";而要使用char c[4]="abc";或者使用char c[]="abc";【例2.10】在下面的程序中,输入“You and we”,输出是输入的内容吗?
#include <stdio.h> void main ( ) { char st[32]; scanf("%s",st); printf(st); printf("\n"); }【解答】不是的。输出是“You”。scanf语句的读入是以空格结束的,所以它只取第1个连续字符串作为输入。要想得到正确的结果,就要放弃scanf函数而改用其他函数。例如,使用gets函数。下面是一个正确的程序。
#include <stdio.h> void main ( ) { char st[32]; printf("输入:"); gets(st); printf("输出:%s\n",st); }运行时输入“You and we”,就能保证输出“You and we”。
相关资源:C语言解惑—指针、数组、函数和多文件编程