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

Pee*_*ush 47 c stdin

我想阅读用户使用C程序输入的名称.

为此,我写道:

char name[20];

printf("Enter name: ");
gets(name);
Run Code Online (Sandbox Code Playgroud)

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

pax*_*blo 81

永远不应该使用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;
}
Run Code Online (Sandbox Code Playgroud)

这允许我设置最大尺寸,将检测是否在线上输入了太多数据,并且还将冲洗线的其余部分,因此它不会影响下一个输入操作.

您可以使用以下内容进行测试:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 不,如果你`scanf("%s")`进入一个20字节的缓冲区并且用户进入一个40字节的行,你就被软管了.`scanf`的整点是扫描格式的,并且没有比用户输入更多_unformatted_ :-) (8认同)
  • @ Marm0t - 通过考虑以下问题来考虑这一点:如果实现它只是一个指向内存片段的指针(类型化为char*),实现如何防止溢出`没有任何参数告诉实现有关目标缓冲区的大小? (7认同)
  • @pstrjds,来自控制台的`scanf`不是_always_ bad,它对数字输入(和家庭作业)等有限的东西很有用.但即使这样,它也不如生产质量应用程序那么强大.即使我需要使用类似`scanf`的操作来解析输入,我也会把它"fgets"到缓冲区然后从那里"sscanf". (2认同)

小智 17

我认为读取用户输入的字符串的最佳和最安全的方法是使用 getline()

以下是如何执行此操作的示例:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    char *buffer = NULL;
    int read;
    unsigned int len;
    read = getline(&buffer, &len, stdin);
    if (-1 != read)
        puts(buffer);
    else
        printf("No line read...\n");

    printf("Size read: %d\n Len: %d\n", read, len);
    free(buffer);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • read = getline(&amp;buffer, &amp;len, stdin); 给出 GCC 警告,例如:gcc -Wall -c "getlineEx2.c" getlineEx2.c: 在函数 main 中:getlineEx2.c:32:5: 警告:从不兼容的指针类型传递 getline 的参数 2 [默认启用] read = getline (&amp;buffer, &amp;len, 标准输入); ^ 在来自 /usr/include/stdio.h:29:0 的文件中,来自 getlineEx2.c:24: /usr/include/sys/stdio.h:37:9: 注意:预期 size_t * 但参数是类型无符号整数 * ssize_t _EXFUN(getline, (char **, size_t *, FILE *)); ^ 编译成功完成。 (2认同)
  • 只是更新getline现在要求len为size_t或unsigned long (2认同)
  • 缺点:POSIX 但不是 ANSI C。 (2认同)

jam*_*lin 6

在POSIX系统上,getline如果可用,您可能应该使用它.

您还可以使用Chuck Falconer的公共域ggets函数,它提供更接近gets但没有问题的语法.(Chuck Falconer的网站已经不再可用了,虽然archive.org有一个副本,我已经为ggets创建了自己的页面.)