处理 C 中的字符串输入

发布于 2024-10-14 10:12:26 字数 128 浏览 9 评论 0原文

如果在使用之前需要声明一个 char 数组,那么如何声明它才能用于存储输入?

例如,用户输入一个句子或一系列单词。如何存储它以便可以对其进行操作?

除了声明一个足够大以处理预期输入的数组之外,正确的方法是什么?

If a char array needs to be declared before it is used, how does one declare one so that is can be used to store input?

e.g. The user enters a sentence or series of words. How is this stored so that it can be manipulated?

What is the correct way rather than just declaring an array which is large enough to handle expected input?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

踏月而来 2024-10-21 10:12:26

如果您正在谈论控制台输入,您别无选择,只能拥有固定大小的缓冲区并使用不允许超过FIXED_SIZE安全功能存储在您的缓冲区中。

一个例子是:

char buff[1024];
fgets(buff, 1024, stdin); // to read from standard input

您必须警告您的用户,任何超过 1023 个的字符都将被忽略。

如果您想访问用户输入的最后一个字符:

printf("%c", buff[strlen(buff)-1]);

If you are talking about console input, you have no choice but to have a FIXED SIZE buffer and use a secure function not allowing more than FIXED_SIZE to be stored on your buffer.

An example would be:

char buff[1024];
fgets(buff, 1024, stdin); // to read from standard input

You must warn your user that any characters beyond 1023th will be ignored.

If you want to access last character the user entered:

printf("%c", buff[strlen(buff)-1]);
余罪 2024-10-21 10:12:26

我通常使用以下函数:

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

它使用缓冲区溢出安全 fgets 和一些支持代码来确定您输入的行是否太长。

当然,您可以读取部分行并执行内存重新分配来存储任意大小的输入字符串,但通常只需设置足够大的上限并允许这样做(例如 1K)就足够了。如果有人输入的姓名或地址超出了这个范围,他们可能只是在愚蠢:-)

我之前实际上已经使用过这个技巧(部分读取和重新分配)来进行用户输入,但说实话,需要它非常罕见,以至于它没有进入我的“重要源代码片段”存储库。

使用fgets可以防止缓冲区溢出的可能性,这对用户输入来说是一个危险。


如果您想测试该代码,请尝试添加:

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

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        printf ("No input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long\n");
        return 1;
    }

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

    return 0;
}

并运行一些示例:(

pax> ./qq
Enter string> hi bob
OK [hi bob]

pax> ./qq
Enter string>
No input

pax> ./qq
Enter string> hi ho the merry oh
Input too long

第二个示例输入 CTRLD,文件立即结束)。

I usually use the following function:

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

It uses the buffer-overflow-safe fgets with some supporting code to figure out if the line you entered was too long.

You can of course, read partial lines and perform memory re-allocations to store an arbitrary sized input string but usually it's more than adequate to just set a large enough upper boundary and allow for that (say 1K for example). If anyone enters more than that for their name or address, they're probably just being silly :-)

I've actually used that trick (partial reads and reallocs) to do user input before but, to be honest, the need for it was so rare that it didn't make it into my "important source code snippets" repository.

The use of fgets prevents the possibility of buffer overflow which is the big danger to user input.


If you want to test that code, try adding:

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

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        printf ("No input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long\n");
        return 1;
    }

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

    return 0;
}

and some sample runs:

pax> ./qq
Enter string> hi bob
OK [hi bob]

pax> ./qq
Enter string>
No input

pax> ./qq
Enter string> hi ho the merry oh
Input too long

(that second one was entering CTRLD, an immediate end of file).

装纯掩盖桑 2024-10-21 10:12:26

通过缓冲区输入 ? (用户将其文本写入一定大小的缓冲区,当缓冲区已满时,程序使用 realloc 更改目标数组的大小)

(您需要使用 char* 而不是 char[] )

Input via buffer ? ( User writes its text to buffer of some size, when buffer is full, programm changes size of target array using realloc )

( you need to use char* instead of char[] )

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文