c - 验证 scanf

标签 c scanf

我还是 C 语言新手,正在尝试验证用户的输入。它必须采用“C”int int int 或“L”int int int 的形式。他们也可以输入任意数量的内容。我测试第一个字符,然后采用后面的 3 或 4 个整数 - 这些整数用于在其他函数中创建一些结构。我无法开始工作的是底部的其他部分。我希望它拒绝任何不是 l/L/c/C 的“类型”

到目前为止我已经

   counter = 0 ;
   while ( type != '\n' )
   {  

      scanf("%c", &type) ;
      if ( type == 'L' || type == 'l')
      {
         scanf(" %d %d %d %d", &llx, &lly, &urx, &ury) ;
         Line line = makeline(llx,lly,urx,ury) ;
         shape = makeshapeline( line ) ;
         box = makeboxshape( shape ) ;
         counter++ ;
      }
      else if ( type == 'C' || type == 'c')
      {
         scanf(" %d %d %d", &x, &y, &rad) ;
         Circle circle = makecircle(x, y, rad) ;
         shape = makeshapecircle( circle ) ;
         box = makeboxshape( shape ) ;
         counter++ ;
      }
      else
      {
         printf("Invalid input\n") ;
         return 0 ;
      }

      if (counter == 1) 
      {
         boxfinal = box ; //On the first run initialise the final box to the first result
      }  

      if (counter > 1)
      {
         boxfinal = makeboxbox( box, boxfinal) ;
      }
   }

非常感谢

最佳答案

您可以考虑使用 %s 而不是 %c 进行 scanf 扫描,然后解析结果字符串。原因是 scanf("%s", str) 会自动忽略空格,但 scanf("%c", char) 会返回空格字符,例如 \n,这是你不想要的。

编辑:作为更一般的说明,正如一些评论中已经提到的那样,如果您只提取字符串、整数,则无需担心在 scanf 系列函数中插入空格,和 float (也许我忘记了),因为这些函数在提取这些数据类型时都忽略输入字符串中的空格。 (除非用户另有指定,否则提取的字符串将始终不含空格。)

关于c - 验证 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19800017/

相关文章:

c - 在C中获取冒号后的数字

c - 仅使用 fprintf 和 fscanf 替换文本文件中的字符串

c - 从 C 文件中读取特定行

c - scanf("%number[^\n], array[N].struct) 的字符串长度

c - 如何将数组包含到 C 函数定义中

c - 如何将 4 位字符数组转换为 Int?

c - 如何从 c 中的文本文件中删除所有文本?

c - 为C代码建立调用树

c - Linux 操作系统 - 来自父进程、子进程、父进程的输入输出管道

c - scanf 的异常行为