首页 > 解决方案 > 使用 scanf() 具有不同数据类型的多个输入

问题描述

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

标签: c++c

解决方案


您的提示说“输入四个整数”,但您还没有声明任何类型的变量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]

另外,请注意您在通话中不需要&before 。strscanf


推荐阅读