【发布时间】:2016-08-30 10:07:59
【问题描述】:
我目前正在研究 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 功能时出现任何错误,请随时告诉我,以便我进行修改。
谢谢
【问题讨论】:
-
现在我明白为什么
gets如此危险了。所以如果没有正确使用,并且你不允许它足够的内存,它会在不知情的情况下溢出,并且可能会覆盖其他重要的内存? -
而
fgets只是通过忽略超出数组限制的任何字符来避免该问题。
标签: c io user-input gets puts