c - 从 C 中的标准输入识别空行

标签 c parsing input

我在尝试识别 C 标准输入中的空行时遇到了一些困难。我有以下代码:

char *line = NULL;
int done = 0;
while (!done) {
   scanf("%m[^\n]", &line);
   if (line != NULL)
      //do something with line
   else
      done = 1;
scanf("\n");
free(line);

这些行应该是用户的命令。假设他只允许调用

insert something
delete something

exit

在任何其他情况下,程序应该输出,比方说,“command not allowed”。我可以在所有情况下都这样做,除了一个 - 当输入中有一个空行时 - 我不知道我怎么能识别一个。我将不胜感激。

最佳答案

不使用 scanf(),而是使用 fgets() 或 *nix getline()

scanf() 旨在读取格式化数据 - 它与 lines 配合得很好。
fgets() 旨在读取(0 个或多个字符直至并包括最后的'\n')并将其转换为通过将空字符 '\0' 附加到目标缓冲区来生成 C 字符串。

char line[100];
while (!done) {
  // scanf("%m[^\n]", &line);
  if (fgets(line, sizeof line, stdin) == NULL) {
    // EOF or input error occurred, for now let us just clear line
    line[0] = 0; 
  }
  // get rid of potential trailing \n
  line[strcspn(line, "\n")] = 0;
  if (line[0]) 
    //do something with line
  else
    done = 1;
} 

关于c - 从 C 中的标准输入识别空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32315006/

相关文章:

iphone - 文件夹中的重复文本?

r - 在 flexdashboard 中上传文件

c - 如何销毁c中的链表?

c - 在 Linux 中无限期休眠一个线程

ruby-on-rails - 加载用于在 Rails 中解析的网页

java - 从 System.in 读入 - Java

php - 如何使用 PHP 解释 HTML5 输入日期值

c - 用于嵌入式系统中 RS232 设备的 Linux 设备驱动程序

c - 有什么方法可以在 C 中取消引用内存地址吗?

PHP : parsing questions then getting the keywords