【问题标题】:Get input string for unkown size, how to stop taking input when a non-alphanumeric character is not on the string?获取未知大小的输入字符串,当字符串上没有非字母数字字符时如何停止输入?
【发布时间】:2020-09-25 07:34:17
【问题描述】:

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

如果你们能建议我实现这一目标的方法或为我指明正确的方向,我将不胜感激。

提前致谢

【问题讨论】:

标签: c string validation malloc user-input


【解决方案1】:

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

【讨论】:

  • @JeanBook:您可以通过单击其分数下方的灰色复选标记来投票并接受此答案。
猜你喜欢
  • 1970-01-01
  • 2014-06-24
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 2017-08-30
相关资源
最近更新 更多