简体   繁体   English

语言:C; 单个scanf()用于1或2个输入

[英]Language: C; Single scanf() for 1 or 2 inputs

What's necessary: 必要条件:

Single scanf()* statement that can accommodate 2 types of input and assign them to before initialized variable/s. 单个scanf()*语句可以容纳2种类型的输入,并将它们分配给初始化的变量之前。

*Or any other function/way that can do what's necessary. *或任何其他可以执行必要功能的功能/方式。

Types of Input: 输入类型:

  1. %c %i - Example: c 56 %c %i示例:c 56
  2. %c - Example: c %c示例:c

The Current Problem: 当前问题:

scanf("%c %i", &c, &i); - Must specify %i , however there are cases of no second argument %i . -必须指定%i ,但是在某些情况下没有第二个参数%i

Examples of possible input: 可能的输入示例:

  • c 567 (same line) c 567(同一行)

  • i 21 (same line) 我21(同一条线)

  • h H

you could read the line using fgets , then use sscanf which isn't interactive, count how many fields you've successfully parsed, and act accordignly: 您可以使用fgets读取该行,然后使用非交互式的sscanf ,计算成功解析了多少个字段,并采取一致的行动:

#include <stdio.h>

int main()
{
 char buffer[100];
 char c;
 int i;

 fgets(buffer, sizeof(buffer), stdin);
 int nb_toks = sscanf(buffer,"%c %i", &c, &i);
 switch (nb_toks)
 {
 case 2:
    printf("%c %i\n",c,i);
    break;
 case 1:
    printf("%c\n",c);
    break;
 default:
   /* some error management */
 }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM