c - 如何读取用户在 C 中输入的字符串?

标签 c stdin

我想使用 C 程序读取我的用户输入的名称。

为此我写道:

char name[20];

printf("Enter name: ");
gets(name);

但是使用gets并不好,那么有什么更好的方法呢?

最佳答案

您应该永远不要使用gets(或具有无限制字符串大小的scanf),因为这会导致缓冲区溢出。将 fgetsstdin 句柄一起使用,因为它允许您限制将放置在缓冲区中的数据。

这是我用于用户行输入的一个小片段:

#include <stdio.h>
#include <string.h>

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

这允许我设置最大大小,将检测是否在该行中输入了太多数据,并将清空该行的其余部分,这样它就不会影响下一个输入操作。

你可以用类似的东西来测试它:

// Test program for getLine().

int main (void) {
    int rc;
    char buff[10];

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        // Extra NL since my system doesn't output that on EOF.
        printf ("\nNo input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long [%s]\n", buff);
        return 1;
    }

    printf ("OK [%s]\n", buff);

    return 0;
}

关于c - 如何读取用户在 C 中输入的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4023895/

相关文章:

node.js - 如何使用 node.js 从 stdin 逐行流式传输并发送到客户端?

c - 有效的stdin阅读c编程

c - 如何使用 apr 从在新进程中运行的程序捕获 stdout/stderr 输出?

Java 到 Win32 加密 API

c - 使用 emWin 和韩语字体时显示错误字形

c++ - $stdin 与 std::istream 的兼容性,使用 swig、C++ 和 Ruby

python - 是否可以访问在标准输入中传递给 python 的 python 脚本的源代码?

c - 如何解决此崩溃的 C 代码问题?

c++ - 是否有生成重复字符串的 C 宏?

python - 使用python的子进程模块打开一个python进程