获取未知大小的输入字符串,当字符串上未包含非字母数字字符时如何停止输入?

问题描述 投票:1回答:1

您好,我正在尝试学习C,并且正在使用DMA,我正在尝试创建一个程序,该程序从用户处获取输入字符串,但我们不知道最大大小(我想分配内存在堆上)我要尝试做的另一件事是,该字符串只能包含字母数字字符,或者当该字符串具有用户输入的逗号或点时停止输入(这可能吗?)

[如果你们可以建议我一种实现这一目标的方法,或者为我指出正确的方向,我将不胜感激。

预先感谢

c string validation malloc user-input
1个回答
0
投票

为了实现您的目标,您应该一次使用getc()getchar()从输入流中读取一个字节,如果是字母数字,则将其存储到目标数组中,使用isalnum()中的<ctype.h>测试,重新分配根据需要使用realloc()数组,并停在EOF和任何其他分隔符上,可能使用ungetc()将该字节推回输入流。使用int变量存储getc()的结果,以便正确检测文件结尾。不要忘了终止目标数组并将其返回给调用者或文件末尾的NULL

您可以在this answer中找到类似目的的示例。

注意,如果您知道输入大小的合理限制,则可以使用scanf()

char buf[1000];
if (scanf(" %999[0-9a-zA-Z]", buf) == 1) {
    // handle the user input
    handle(buf);
    // read and discard the separator(s)
    scanf("%*[^0-9a-zA-Z]");
} else {
    // no pending word: either end of file or a non alphanumeric character pending
}

还请注意,GNU系统具有一个扩展,该扩展允许scanf将目标数组分配为适当的大小,仅受可用内存限制:

char *str;
if (scanf(" %m[0-9a-zA-Z]", &str) == 1) {
    // handle the user input
    handle(str);
    // free the allocated string
    free(str);
    // read and discard the separator(s)
    scanf("%*[^0-9a-zA-Z]");
} else {
    // no pending word: either end of file or a non alphanumeric character pending
}
    
© www.soinside.com 2019 - 2024. All rights reserved.