C 语言中输入和输出的同命函数215
在 C 语言中,有许多函数用于输入和输出操作。其中一些函数有着相似的名称,但它们的行为却有细微的差别。最常用于输入和输出的同命函数是 getchar()、putchar()、getc() 和 putc()。
getchar() 和 putchar()
getchar() 函数从标准输入(通常是键盘)读取一个字符,而 putchar() 函数将一个字符写入标准输出(通常是屏幕)。以下示例演示了如何使用这两个函数:```c
#include
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c", ch);
return 0;
}
```
在上面的示例中,getchar() 函数读取用户输入的字符并将其存储在变量 ch 中。然后,putchar() 函数将 ch 中的字符写入屏幕。
getc() 和 putc()
getc() 和 putc() 函数与 getchar() 和 putchar() 函数类似,但它们用于从文件(而不是标准输入)读取和写入字符。以下是它们的语法:```c
int getc(FILE *stream);
int putc(int ch, FILE *stream);
```
其中,stream 是指向文件的指针。以下示例演示了如何使用 getc() 和 putc() 函数:```c
#include
int main() {
FILE *fp;
char ch;
fp = fopen("", "r");
if (fp == NULL) {
perror("Error opening file");
return -1;
}
while ((ch = getc(fp)) != EOF) {
putc(ch, stdout);
}
fclose(fp);
return 0;
}
```
在上面的示例中,getc() 函数从 文件读取字符并将其存储在变量 ch 中。然后,putc() 函数将 ch 中的字符写入屏幕。
比较
下表比较了 getchar()、putchar()、getc() 和 putc() 函数之间的主要区别:| 函数 | 用途 | 输入/输出源 |
|---|---|---|
| getchar() | 从标准输入读取字符 | 键盘 |
| putchar() | 将字符写入标准输出 | 屏幕 |
| getc() | 从文件读取字符 | 文件 |
| putc() | 将字符写入文件 | 文件 |
getchar()、putchar()、getc() 和 putc() 函数是 C 语言中用于输入和输出操作的同命函数。它们的行为有细微的差别,因此在使用时选择正确的函数很重要。通过了解这些函数之间的差异,您可以编写出更有效、更可靠的 C 程序。
2024-11-22
上一篇:C 语言:高效输出用户输入的数字
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html