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

时间:2018-06-02 16:17:58

标签: c++ c

我正在开展一些项目,但我遇到了一个问题。 我无法正常使用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);
}

1 个答案:

答案 0 :(得分:1)

您的提示符为"输入四个整数",但您尚未声明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 %i\n", str, hex, c, anotherint);

我使用%99s来确保我没有溢出char str[100]

此外,请注意&来电中str之前您不需要scanf