c - 使用 scanf 验证特定数量的参数 (int)?

标签 c validation input scanf

我需要根据用户输入制作一个带有网格的“connect 4”程序。如何在没有任何缓冲的情况下检测扫描的整数数量,或者在不等待另一个参数的情况下“接受”短输入?在本例中,我希望用户在程序开始时输入 3 个值。

 Example 1
 ./connectn.out 5 20
 Not enough arguments entered

 Example 2
 ./connectn.out 13 2 3 4 5
 Too many arguments entered

最佳答案

您需要的是 argc 和 argv 参数。您可以使用 argc 作为参数计数,使用 argv 作为参数本身。

这里是一个示例代码:

#include <stdio.h>
#include <string.h>

int main (int argc, char * argv[])
{
  // Check the argument count first
  if (argc != 4)
  {
    if (argc > 4)
    {
      printf("Too many arguments entered!\n");
    }
    else
    {
      printf("Not enough arguments entered!\n");
    }
    return -1;
  }
  else
  {
    // Check a specific argument (-h)
    if (strcmp(argv[3], "-h") != 0)
    {
      printf("Invalid option!\n");
      return -1;
    }
  }

  printf("Hello World.\n");
  return 0;
}

请注意,在 ./connectn.out 5 20 中,argc 为 3。因为“connectn.out”也算在内。

这是一些示例输出:

./out 1 2
Not enough arguments entered!
./out 1 2 3 4
Too many arguments entered!
./out 1 2 -a
Invalid option!
./out 1 2 -h 4
Too many arguments entered!
./out 1 2 -h
Hello World.

希望这有帮助。

巴里斯

关于c - 使用 scanf 验证特定数量的参数 (int)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47373168/

相关文章:

c - 通过使用另一个要求用户输入的函数来停止计时函数

c++ - 输入验证将数字放入 vector 中

JavaScript 验证错误

javascript - 在 React 中单击按钮时,如何在输入字段的任意位置直接插入文本?

Java 程序打印出 0 而不是百分比

javascript - 从 input.value 添加对象属性

c - fprintf、printf 和 sprintf 之间的区别?

c - 更新 MD5 哈希值?

c - Little Endian 和 Big Endian 中的内存表示字符串

spring - 如何在 Spring 4 中开启注解驱动验证?