如何读取字符串用户在C进入 [英] how to read string entered by user in c

查看:132
本文介绍了如何读取字符串用户在C进入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读通过C程序我输入的用户名

I want to read the name entered by my user using C programmes

为此,我写道:

char name[20];

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

但使用获得不是很好,所以建议我一个更好的办法。

but using gets is not good so suggest me a better way.

推荐答案

您应该的从不的使用获得(或 scanf函数采用无界字符串大小),因为打开您缓冲区溢出。使用与fgets 标准输入处理,因为它可以让你限制将被放置在缓冲区中的数据。

You should never use gets (or scanf with an unbounded string size) since that opens you up to buffer overflows. Use the fgets with a stdin handle since it allows you to limit the data that will be placed in your buffer.

下面是一个小片段我使用的线路输入从用户:

Here's a little snippet I use for line input from the user:

#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;
}

此允许我设置最大大小,如果就行输入数据太多会检测,并且将刷新行的其余部分,以及因此不会影响到下一个输入操作。

This allows me to set the maximum size, will detect if too much data is entered on the line, and will flush the rest of the line as well so it doesn't affect the next input operation.

您可以用类似测试:

// 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进入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆