使用 scanf() 具有不同数据类型的多个输入

Multiple inputs with different data types using scanf()

本文关键字:数据类型 输入 scanf 使用      更新时间:2023-10-16

我正在做一些项目,但我被困在一个问题上。 我无法正常使用scanf()功能。我想扫描具有不同数据类型的多个输入。 但我不知道问题是什么。没有编译错误。

#include "stdio.h"
int main()
{
unsigned char minx[1024], x, y, z;
printf("Enter four ints: ");
scanf( "%s %x %c %i", &minx, &x, &y, &z);
printf("You wrote: %s %x %c %i", minx, x, y, z);
}

提示显示"输入四个整数",但尚未声明任何类型int的变量。 你有

unsigned char minx[1024], x, y, z;

它为您提供一个包含 1024 个无符号字符的数组和三个单独的无符号字符。

然后你写了

scanf( "%s %x %c %i", &minx, &x, &y, &z);

你说你没有收到任何编译器错误。 如果可能的话,我必须鼓励你得到一个更好的编译器! 我的警告我关于这条线上的各种事情:

format specifies type 'char *' but the argument has type 'unsigned char (*)[1024]'
format specifies type 'unsigned int *' but the argument has type 'unsigned char *'
format specifies type 'int *' but the argument has type 'unsigned char *'

如果要输入字符串、十六进制整数、字符和另一个整数,请使变量类型匹配:

char str[100];
int hex;
char c;
int anotherint;
scanf("%99s %x %c %i", str, &hex, &c, &anotherint);
printf("You wrote: %s %x %c %in", str, hex, c, anotherint);

我用%99s来确保我不会溢出char str[100]

另请注意,在strscanf调用之前不需要&