C语言中getchar()、fgetc()和getc()的返回值类型


getchar()、fgetc()和getc()函数在C编程中的详细信息如下:

getchar()函数

getchar()函数从标准输入stdin获取一个字符。它返回以整数形式读取的字符,如果发生错误则返回EOF。

演示此功能的程序如下:

示例

 在线演示

#include <stdio.h>

int main (){
   int i;

   printf("Enter a character: ");
   i = getchar();

   printf("
The character entered is: ");    putchar(i);    return(0); }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

上述程序的输出如下:

Enter a character: G
The character entered is: G

现在让我们理解上述程序。

使用getchar()函数获得的值存储在整数变量i中。然后使用putchar()显示字符值。显示此功能的代码片段如下:

int i;

printf("Enter a character: ");
i = getchar();

printf("
The character entered is: "); putchar(i);

fgetc()函数

fgetc()函数从文件流(指向FILE对象的指针)获取一个字符。此函数返回以整数形式读取的字符,如果发生错误则返回EOF。

演示此功能的程序如下:

示例

 在线演示

#include <stdio.h>

int main (){
   FILE *fp;
   fp = fopen("file.txt", "w");
   fprintf(fp, "Apple");
   fclose(fp);

   int i;

   fp = fopen("file.txt","r");
   
   if(fp == NULL){
      perror("Error in opening file");
      return(-1);
   }

   while((i=fgetc(fp))!=EOF){
      printf("%c",i);
   }

   fclose(fp);
   return(0);
}

输出

上述程序的输出如下:

Apple

现在让我们理解上述程序。

首先,创建文件并将数据“Apple”存储在其中。然后关闭文件。显示此功能的代码片段如下:

FILE *fp;
fp = fopen("file.txt", "w");
fprintf(fp, "Apple");
fclose(fp);

文件再次以读取模式打开。如果fp为NULL,则显示错误消息。否则,使用fgetc()函数显示文件的内容。显示此功能的代码片段如下:

fp = fopen("file.txt","r");

if(fp == NULL){
   perror("Error in opening file");
   return(-1);
}

while((i=fgetc(fp))!=EOF){
   printf("%c",i);
}

fclose(fp);

getc()函数

getc()函数从指定的流中获取一个字符。它返回以整数形式读取的字符,如果发生错误则返回EOF。

演示此功能的程序如下:

示例

 在线演示

#include <stdio.h>

int main (){
   int i;

   printf("Enter a character: ");
   i = getc(stdin);

   printf("
The character entered is: ");    putchar(i);    return(0); }

输出

上述程序的输出如下:

Enter a character: K
The character entered is: K

现在让我们理解上述程序。

getc()函数从指定的stdin流获取一个字符。此值存储在int变量i中。然后使用putchar()显示字符值。显示此功能的代码片段如下:

int i;

printf("Enter a character: ");
i = getc(stdin);

printf("
The character entered is: "); putchar(i);

更新于:2020年6月26日

2K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告