【问题标题】:Validating a specific number of arguments (int) using scanf?使用scanf验证特定数量的参数(int)?
【发布时间】:2018-05-02 13:26:05
【问题描述】:

我需要根据用户输入制作一个带有网格的“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

【问题讨论】:

  • 为什么不在main()中声明argvargc参数呢?然后您可以确定argc 是否等于三。我建议看看this 教程。
  • scanf 用于程序提示输入。您要的是命令行参数,它们完全不同。只需检查argc 即可查看提供了多少。

标签: c validation input scanf


【解决方案1】:

你需要的是 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.

希望这会有所帮助。

巴里斯

【讨论】:

    猜你喜欢
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    相关资源
    最近更新 更多