gpt4 book ai didi

c - getchar/putchar、gets/puts 和 fgets/fputs(C 语言)之间有什么区别?

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:03 25 4
gpt4 key购买 nike

我目前正在研究 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 - 将单个字符写入标准输出。

关于c - getchar/putchar、gets/puts 和 fgets/fputs(C 语言)之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39224580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com