c - 同时使用 scanf 和 gets

标签 c

我知道我在问基本问题。我在 C 程序中使用 scanfgets 时遇到问题。当我使用 scanf 时,gets 没有执行。示例如下:

void fun() {
    char str[10];
    printf("Enter the string");
    gets(str);
    printf("Entered string is %s\n", str);
}

int main() {
    int val;
    printf("Enter the value\n");
    scanf("%d", &val);
    fun();
}

如果我运行这个程序,gets 不会执行。输入值后。它不等待输入字符串。输出为 Enter the stringEntered string is。但是如果注释 scanf,它会等待 gets 中的输入并正常工作。谁能告诉我,我做错了什么。

最佳答案

嗯,这里的“正确”答案很简单:永远不要使用 gets。就这么简单。它甚至已从 C11 标准中删除。

原因是,你没有办法限制输入的数量,所以无论你保留多大的缓冲区,用户仍然可以产生足够的输入来导致缓冲区溢出。

如果您正在编写标准 C,您可能应该使用 fgets。如果您使用 gcc(如 MinGW 或 Cygwin),您应该使用 getline在 Window 下),或任何支持最新 POSIX 标准的现代类 Unix 操作系统。


然后是实际问题,忽略 gets 的问题。问题是,scanf 将包括 enter press 在内的行的其余部分留在了输入流中。一个强大的解决方案是编写一个函数,它将读取输入直到下一个换行符,类似于这个未经测试的函数:

// this function reads given file until newline or end of file or error,
// and returns last value read
int eatLine(FILE *fp) {
    for(;;) {
        int ch = getc(fp);
        if (ch == '\n' || ch < 0) return ch;
    }
}

用法:

if (scanf("%d", &myint) != 1) exit(0); // exit on invalid input
if (eatLine(stdin) < 0) exit(0); // read and ignore rest of the line, exit on eof

还有其他解决方案,例如读取一行缓冲并对​​其使用sscanf,以上只是一种简单的可能性。

关于c - 同时使用 scanf 和 gets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26815982/

相关文章:

c - 带有 iommu=on 且没有 VFIO 的 Linux 用户空间 DMA

c - 为什么不打印我的 char 数组指针?

c++ - 我需要释放指向函数的指针吗?

C 从函数返回 char 数组

C/C++ 预处理器 - 'Charify'

c - nrf51 定时器驱动程序代码错误

c - 用指针 C 填充结构

c - 关于从文件读取多个整数,将它们转换为二进制,然后将它们打印到屏幕的指南?

c - 我正在尝试制作一个可以根据用户在 C 中的选择来运行不同功能的程序

c - 将 GSL 库链接到 Matlab MEX 时如何修复 'unknown type name' 错误