C库提供了三个读取字符串的函数:gets( ) fgets( ) scanf( )。
gets()---get string 从系统的标准输入设备(通常是键盘)获得一个字符串。因为字符串没有预定的长度,所以gets()需要知道输入何时结束。解决办法是在读字符串直到遇到一个换行符(/n),按回车键可以产生这个字符。它读取换行符之前(不包括换行符)的所有字符,在这些字符后加一个空字符(/0)。它会丢弃换行符。
定义函数 char *gets(char *s)
返回值 gets()若成功则返回s指针,返回NULL则表示有错误发生。
- /* name1.c -- reads a name */
- #include <stdio.h>
- #define MAX 81
- int main(void)
- {
- char name[MAX]; /* 分配空间 */
- printf("Hi, what's your name?/n");
- gets(name); /* 把字符串放进name数组中 */
- printf("Nice name, %s./n", name);
- return 0;
- }
fgets()---是为文件I/O设计的
定义函数 fgets(char *s,int size,FILE *stream)
返回值 若成功则返回s指针,返回NULL则表示有错误发生。
fgets()用来从参数stream所指的文件内读入字符并存到参数s所指的内存空间,知道出现换行符、读到文件尾或者是读了size-1个字符为止。fgets()会把换行符存储到字符串里。
- /* name3.c -- reads a name using fgets() */
- #include <stdio.h>
- #define MAX 81
- int main(void)
- {
- char name[MAX];
- char * ptr;
- printf("Hi, what's your name?/n");
- ptr = fgets(name, MAX, stdin);
- printf("%s? Ah! %s!/n", name, ptr);
- return 0;
- }
运行结果
Hi, what's your name?
Jon Dough
Jon Dough
? AH! Jon Dough
!
scanf( )---格式化字符串输入
定义函数 int scanf(const char *format,。。。。。)
返回值 成功则返回参数数目,失败则返回-1
参数 size---允许输入的数据长度
l ---以long int或double型保存
h ---short int型保存
s ---字符串
c ---字符
- /* scan_str.c -- using scanf() */
- #include <stdio.h>
- int main(void)
- {
- char name1[11], name2[11];
- int count;
- printf("Please enter 2 names./n");
- count = scanf("%5s %10s",name1, name2);
- printf("I read the %d names %s and %s./n",
- count, name1, name2);
- return 0;
- }
运行结果
Please enter 2 names.
Jesse Jukes
I read the 2 names Jesse and Jukes.
Please enter 2 names.
Liza Applebottam
I read the 2 names Liza and Applebotta.
Please enter 2 names.
Portensia Callowit
I read the 2 names Porte and nsia.