简体   繁体   English

是否可以在 c 中的一个 scanf() 中获得两个不同数据类型的输入?

[英]Is it possible to get two inputs of different datatypes in one scanf() in c?

I want to get the command as input like我想将命令作为输入获取

<char><number><number>

so is it possible to get it using one scanf() function in c ?那么是否可以在 c 中使用一个scanf()函数来获得它?

int i,j; 
char c; 
scanf("%c%d%d",&c, &i, &j);

I don't think that will work because the compiler will consider that as something together rather than one character, and two integers but to take the input in this format ie to make the compiler understand that you can take the entire line as a string and then parse the string to extract the character and the integers我认为这行不通,因为编译器会将其视为一起而不是一个字符和两个整数,但要以这种格式输入,即让编译器了解您可以将整行作为一个字符串和然后解析字符串以提取字符和整数

char a[1000],c; int x,y;
scanf("%s",a);
c = a[0];
x = a[1] - '0';
y = a[2] - '0';

Also, @BLUEPIXY gave even better solution to your problem!此外,@BLUEPIXY 为您的问题提供了更好的解决方案!

You can get more than 1 input in 1 scanf as the following:您可以在 1 个 scanf 中获得 1 个以上的输入,如下所示:

char ch, string[100];
int number;

printf("--char--/--number--/--string--");
scanf(" %c%d %s",&ch,&number,&string[0]); // -> be careful about the whitespaces

printf("%c\n",ch);
printf("%d\n",number);
printf("%s\n",string);

You dont need to use spaces or \\n to enter your input.您不需要使用空格或 \\n 来输入您的输入。

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

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