使用 scanf 或 fgets 在 c 函数中获取特定的用户输入和参数计数?

Getting specific user input and argument count in function in c using scanf or fgets?

我正在尝试使用 scanffgets 让用户输入函数。

我在写C.

用户必须输入 2 个(正)整数。两者之间的差值必须为 1。 我必须检查实际上是否只给出了 2 个参数。

函数应该 return 给定整数中较小的一个,如果:

函数应该 return -1 如果:

函数应该 return -2 如果:

我比较整数和 return 正确的值没有问题,我的问题是输入。 到目前为止,我已经尝试过这种方法:

1.)

int getInput(){
  int user_input_nod_1;
  int user_input_nod_2;
  scanf("%d %d",&user_input_nod_1,&user_input_nod_2)
  (...)
}

这里的问题是我无法知道用户是否输入了超过 2 个整数。

2.)

int getInput(){
  int user_input_nod_1;
  int user_input_nod_2;
  char user_input_over;
  scanf("%d %d",&user_input_nod_1,&user_input_nod_2)
  scanf("%c",&user_input_over)
  if(user_input_over != '[=11=]'){
     return -1;
  }
  (...)
}

此处程序 returns -1 如果给出了两个以上的参数,并且在给定两个参数时完美运行,但如果只给定一个 scanf 等待第二个输入的无穷大(即使在按下 enter 之后)。用户不知道如何结束流 (cmd+d,...)

3.)

int getInput(){    
  char input_nods[10];

  if(fgets(input_nods, 10, stdin) != NULL)
  {
     puts(input_nods);
  }

  char input_c1;
  char input_c2;
  char input_nod_over;

  sscanf(input_nods,"%c %c %c",&input_c1, &input_c2, &input_nod_over);

  char *nod_check_1, *nod_check_2;
  int input_nod_1 = strtol(&input_c1, &nod_check_1, 10);
  int input_nod_2 = strtol(&input_c2, &nod_check_2, 10);

  if (input_nod_over != '[=12=]' || input_nods[2] == ' ' || input_nods[2] == '[=12=]')
  {
      return -1;
  }
}

当给定 0-9 范围内的整数时,这非常有效。一旦输入有两位数字,sscanf 就会被 fgets 保存在 input_nodes[].

中的空格弄乱

有什么方法可以实现我想要的吗? 谢谢。

第三种方式,可以使用input_nod_1input_nod_2,完全不用sscanf函数

在第一次使用 strtol 时,您必须检查 nod_check_1 是否为空(或者 space 如果您想更具体一点),并且在第二次使用时你必须检查 nod_check_2NULL.

但是,我会使用 long 作为 strtol 结果(为了避免 long->int 转换溢出),并检查 errno 以防 strtol returns 0.

我现在使用这个循环实现了它:

int user_input_nod_1;
int user_input_nod_2;

char buf[BUFSIZ], junk[BUFSIZ];

fprintf( stderr, "> " );              
while ( fgets( buf, sizeof(buf), stdin ) != NULL )
{
    if ( sscanf( buf, "%i%i%[^\n]", &user_input_nod_1, &user_input_nod_2, junk ) == 2 )
        break;
    fprintf( stderr, "[ERR] \n" );
    fprintf( stderr, "> " );
}

(使用“>”作为某种光标...)