C 语言 getchar() 函数

17 Mar 2025 | 4 分钟阅读

在本节中,我们将学习 C 编程语言中的 getchar() 函数。 getchar() 函数是一个非标准函数,其含义已在 stdin.h 头文件中定义,用于接受用户输入的单个字符。换句话说,它是 C 库函数,从 stdin 获取单个字符(无符号字符)。然而,getchar() 函数与 getc() 函数类似,但 C 编程语言的 getchar() 和 getc() 函数之间存在细微差别。getchar() 从标准输入读取单个字符,而 getc() 从任何输入流读取单个字符。

Getchar() function in C

语法

它没有任何参数。但是,它将读取的字符作为无符号字符返回一个 int 值,如果文件出现错误,则在文件末尾返回 EOF

现在我们编写几个 getchar() 函数程序,以在 C 中接受单个字符并使用 putchar() 函数打印它们。

使用 getchar() 函数读取单个字符

让我们考虑一个在 C 中使用 getchar() 函数接收单个字符的程序。

Program.c

输出

Enter a character
A
 You have passed A

正如我们在上面的程序中看到的,它在运行时使用 getchar() 函数从用户那里接收单个字符。获取字符后,它通过 putchar() 函数打印该字符。

使用 getchar() 函数从用户那里读取 n 个字符

让我们考虑一个在 C 中使用 getchar() 函数读取 n 个字符的程序。

Getchar.c

输出

Enter a character ( If we want to exit.. press #)
A

 We have entered the character: A
 We have entered the character:

B

 We have entered the character: B
 We have entered the character:
C

 We have entered the character: C
 We have entered the character:

正如我们在上面的输出中看到的,一个 while 循环不断地从用户那里接收字符,直到用户没有输入 # 字符。这里 getchar() 函数从标准输入接收单个字符并将它们赋值给 ch 变量。而 putchar() 函数打印读取的字符。

使用 scanf() 函数读取单个字符

让我们考虑一个在 C 中使用 scanf() 库函数读取字符的程序。

Prog.c

输出

Enter the character
A
 You have entered A

正如我们所看到的,当我们执行上面的程序时,它使用 scanf() 库函数而不是 getchar() 函数接收单个字符或一组字符。但有一个小区别;scanf() 函数可以从用户那里接收单个或一组字符,而 getchar() 函数只能接收单个字符。

这里我们再次执行上面的程序,这次,它显示以下结果。

使用 do-while 循环读取字符

让我们考虑一个在 C 中使用 do-while 和 getchar() 函数读取字符的程序。

Dowhile1.c

输出

Enter the characters from the keyboard (Press Enter button to stop).
Well b47gvb come
Entered characters are Well b47gvb come

在上面的程序中,do-while 循环不断地接收字符,直到用户按下 ENTER 键退出循环。


下一个主题C 语言流程图