在C语言中,接受键盘的值可以通过几种方式来实现:scanf()、getchar()、gets()。其中,scanf()
是最常用的方法,因为它可以接受多种类型的输入。使用scanf()
时需要注意输入缓冲区的问题。例如,当你使用scanf()
读取整数后,再读取字符时,可能会出现意想不到的结果,因为缓冲区中可能还残留有回车符。这些问题可以通过清空缓冲区来解决。以下是对scanf()
函数的详细描述。
一、scanf()函数
scanf()
函数是C语言中最常用的输入函数,它可以根据格式化字符串读取并存储多个不同类型的输入值。
1、基本用法
scanf()
函数的基本用法如下:
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %dn", num);
return 0;
}
在这个例子中,程序会等待用户输入一个整数,然后将其存储在变量num
中。
2、读取多个值
scanf()
函数还可以一次读取多个值,例如:
#include <stdio.h>
int main() {
int num1, num2;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
printf("You entered: %d and %dn", num1, num2);
return 0;
}
程序会等待用户输入两个整数,并将其分别存储在变量num1
和num2
中。
3、处理字符和字符串
使用scanf()
读取字符和字符串时,需要注意以下几点:
#include <stdio.h>
int main() {
char ch;
char str[100];
printf("Enter a character: ");
scanf(" %c", &ch); // 注意前面的空格
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %c and %sn", ch, str);
return 0;
}
在读取字符时,前面加一个空格可以跳过之前的空白字符(如回车符)。
4、缓冲区问题及解决方法
当我们使用scanf()
读取输入时,输入缓冲区中可能会残留一些字符,这可能会导致后续的读取操作出现问题。例如:
#include <stdio.h>
int main() {
int num;
char ch;
printf("Enter an integer: ");
scanf("%d", &num);
printf("Enter a character: ");
scanf("%c", &ch); // 这里会直接读取到回车符
printf("You entered: %d and %cn", num, ch);
return 0;
}
在这个例子中,scanf("%c", &ch)
会直接读取到回车符,而不是用户输入的字符。为了避免这种情况,我们可以在读取字符之前清空输入缓冲区:
#include <stdio.h>
int main() {
int num;
char ch;
printf("Enter an integer: ");
scanf("%d", &num);
while(getchar() != 'n'); // 清空缓冲区
printf("Enter a character: ");
scanf("%c", &ch);
printf("You entered: %d and %cn", num, ch);
return 0;
}
这样可以确保scanf("%c", &ch)
读取到的是用户输入的字符。
二、getchar()函数
getchar()
函数可以从标准输入中读取一个字符。它通常用于读取单个字符或逐字符读取输入。
1、基本用法
getchar()
的基本用法如下:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %cn", ch);
return 0;
}
程序会等待用户输入一个字符,并将其存储在变量ch
中。
2、逐字符读取输入
我们可以使用getchar()
逐字符读取输入,直到遇到换行符或文件结束符为止:
#include <stdio.h>
int main() {
char ch;
printf("Enter some text (end with Enter): ");
while((ch = getchar()) != 'n') {
putchar(ch);
}
printf("n");
return 0;
}
程序会逐字符读取用户输入,并将其逐字符输出。
三、gets()函数
gets()
函数用于读取一行字符串,直到遇到换行符为止。需要注意的是,gets()
函数有安全隐患,容易引起缓冲区溢出。因此,在实际开发中,建议使用更安全的fgets()
函数。
1、基本用法
gets()
的基本用法如下:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("You entered: %sn", str);
return 0;
}
程序会等待用户输入一行字符串,并将其存储在数组str
中。
2、使用fgets()替代gets()
为了避免缓冲区溢出问题,我们可以使用更安全的fgets()
函数:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: %sn", str);
return 0;
}
fgets()
函数需要指定读取的最大字符数,并且它会保留换行符。因此,我们通常需要手动去除换行符:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// 去除换行符
str[strcspn(str, "n")] = '