如何使用return类型的"fgetc"吹代码?
how to use the return type of "fgetc" blow the code?
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
在代码中,fgetc(fp) 使用 int 作为此 return 类型,所以为什么我们使用 "printf("%c",c);"而不是 "print("%d",c);"
在 printf
格式字符串中,%c
表示“将 int
参数转换为 unsigned char
并打印它作为代码的字符。”
%d
表示“将 int
参数转换为十进制数字并打印该数字。”
%c
会将其打印为 character
%d
会将其打印为十进制表示形式。
示例:
void printAsChar(const char *x)
{
while(*x)
{
printf("%c\n", *x++);
}
}
void printAsDecimal(const char *x)
{
while(*x)
{
printf("%d\n", *x++);
}
}
int main(void)
{
printAsChar("hello");
printf("------------\n");
printAsDecimal("hello");
}
https://godbolt.org/z/rx8oqaMnT
结果:
h
e
l
l
o
------------
104
101
108
108
111
104
是'h'
的ASCII码,'e'
的101
码等
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
在代码中,fgetc(fp) 使用 int 作为此 return 类型,所以为什么我们使用 "printf("%c",c);"而不是 "print("%d",c);"
在 printf
格式字符串中,%c
表示“将 int
参数转换为 unsigned char
并打印它作为代码的字符。”
%d
表示“将 int
参数转换为十进制数字并打印该数字。”
%c
会将其打印为 character
%d
会将其打印为十进制表示形式。
示例:
void printAsChar(const char *x)
{
while(*x)
{
printf("%c\n", *x++);
}
}
void printAsDecimal(const char *x)
{
while(*x)
{
printf("%d\n", *x++);
}
}
int main(void)
{
printAsChar("hello");
printf("------------\n");
printAsDecimal("hello");
}
https://godbolt.org/z/rx8oqaMnT
结果:
h
e
l
l
o
------------
104
101
108
108
111
104
是'h'
的ASCII码,'e'
的101
码等