在 C 中读取用户输入的可变长度字符串 [英] Reading in a variable length string user input in C

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

问题描述

我正在尝试读取可变长度的用户输入并执行一些操作(例如在字符串中搜索子字符串).

I am trying to read in a variable length user input and perform some operation (like searching for a sub string within a string).

问题是我不知道我的字符串有多大(文本很可能是 3000-4000 个字符).

The issue is that I am not aware how large my strings (it is quite possible that the text can be 3000-4000 characters) can be.

我附上了我尝试过的示例代码和输出:

I am attaching the sample code which I have tried and the output:

char t[],p[];
int main(int argc, char** argv) {
    fflush(stdin);
    printf(" enter a string
");
    scanf("%s",t);

    printf(" enter a pattern
");
    scanf("%s",p);

    int m=strlen(t);
    int n =strlen(p);
    printf(" text is %s %d  pattrn is %s %d 
",t,m,p,n);
    return (EXIT_SUCCESS);
}

输出是:

enter a string
bhavya
enter a pattern
av
text is bav 3  pattrn is av 2

推荐答案

请不要永远使用不安全的东西,比如 scanf("%s") 或我个人的不喜欢的,gets() - 没有办法防止缓冲区溢出.

Please don't ever use unsafe things like scanf("%s") or my personal non-favourite, gets() - there's no way to prevent buffer overflows for things like that.

您可以使用更安全的输入法,例如:

You can use a safer input method such as:

#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] != '
') {
        extra = 0;
        while (((ch = getchar()) != '
') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

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

然后您可以设置最大大小,它会检测该行是否输入了过多数据,并刷新该行的其余部分,以免影响您的下一个输入操作.

You can then set the maximum size and it will detect if too much data has been entered on the line, flushing the rest of the line as well so it doesn't affect your next input operation.

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

You can test it with something like:

// 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 ("
No input
");
        return 1;
    }

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

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

    return 0;
}

这篇关于在 C 中读取用户输入的可变长度字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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