我目前正在研究C语言中的输入和输出,我发现大约有十亿种不同的获取输入的方法,例如getch,getchar,gets和fgets,以及与输出相同的方法(putchar,puts,fputs等) )。
所有这些不同的I / O方法都使我感到困惑,因此我来问一下上述功能之间的基本区别是什么。
我还使用这些不同的功能编写了一些代码,并根据我所学的知识对它们的工作方式进行了评论,但是我不确定我的理解是否正确。我在其他地方也阅读过它们,但是解释非常复杂,而且似乎不连贯。
因此,有人可以告诉我是否正确使用它们,如果不正确,应该如何使用它们以及它们之间的主要区别是什么?
这是我的代码:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
void individualCharacters()
{
char theChar;
while ((theChar = getchar()) != '~') { // getchar() stores all characters in a line buffer as it is entered until newline is entered
putchar(theChar); // putchar() prints the characters in the line buffer and does not print a newline, line buffering depends on compiler
}
}
void withoutF()
{
char name[50];
printf("What is your name? ");
gets(name); // receives a string until newline is entered, newline is then replaced with string terminator, array limit should not be passed
puts("Hi"); // only prints one string at a time and adds the newline because gets() previously replaces the newline
puts(name);
}
void withF()
{
char name[50];
printf("What is your name? ");
fgets(name, 50, stdin); // does add a newline so the newline takes up one space in the array, it stores input until either newline is entered or array limit is reached
fputs("Hi ", stdout); // does not print a newline but prints the string input up to the array limit
fputs(name, stdout);
}
void main()
{
//sum();
//individualCharacters();
//withoutF();
//withF();
//printRandomString();
}
这些只是我编写的一些函数,它们以不同的方式获取输入和显示输出,但是我很难理解为什么会有这么多种不同的方式。
如果我在使用I / O功能时遇到任何错误,请随时告诉我,以便我进行修改。
谢谢
fgets
-SIZE-1
从指定的流中最多将字符读取到缓冲区中,如果有空间,则包括结尾的换行符。在缓冲区的末尾添加一个0终止符,使其成为有效的C字符串:
char buffer[SIZE];
if ( fgets( buffer, sizeof buffer, stdin ) ) // read from standard input
do_something_with( buffer );
else
error();
成功时,fgets
返回输入缓冲区的地址。在失败或文件结束时,它返回NULL
。
fgetc
-从指定的输入流中读取单个字符并返回它:
FILE *input_stream = fopen( "some_file", "r" );
int c;
while ( (c = fgetc( input_stream )) != EOF )
do_something_with( c );
gets
-C99之后不推荐使用,从C2011中完全删除。像一样fgets
,它将从标准输入中读取字符序列到缓冲区中,并添加一个0终止符,但是fgets
与之不同的是,它没有提供限制输入的机制,这使其成为一种流行的恶意软件利用程序。同样,它不会将尾随换行符存储到缓冲区。保证使用它会在您的代码中引入一个故障点。假装您从未听说过它。
getc
-与相同fgetc
,除了可以实现为宏。
getchar
-从标准输入中读取单个字符:
int c;
...
while( (c = getchar()) != EOF )
do_something_with( c );
fputs
-将字符串写入指定的输出流:
char str[SIZE];
...
fputs( str, output_stream );
fputc
-将单个字符写入指定的输出流:
while ( i < strsize )
fputc( str[i], output_stream );
putc
-与相同fputc
,除了可以实现为宏
putchar
-将单个字符写入标准输出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句