为什么我不能 scanf 和 printf 一个整数?

Why can't I scanf and printf an integer?

#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <sstream>

using namespace std;

struct person
{
    int age;
    string name[20], dob[20], pob[20], gender[7];
};

int main ()
{
    person person[10];
    cout << "Please enter your name, date of birth, place of birth, gender, and age, separated by a space.\nFor example, John 1/15/1994 Maine Male 20: ";
    scanf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
    printf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
    return 0;
}

我尝试扫描并打印用户的年龄,但它为我提供了 2749536 的 person.age 值。这是为什么?

您应该将 age 的类型从 float 更改为 int

否则,使用 %f 作为 float 类型。

此外,根据 Mr. dasblinkenlight 的建议,将 string 更改为 char

然后,在 printf() 的情况下,从 &person[0].age 中删除 &。您想要打印变量的值,而不是地址。 FWIW,要打印地址,您应该使用 %p 格式说明符并将参数转换为 (void *).

不要混淆它们并期望它们起作用。如果您向提供的格式说明符提供不正确类型的参数,最终将导致 undefined behavior.

故事的寓意:启用编译器警告。大多数时候,他们会警告您潜在的陷阱。

您正在将值的地址传递给 printf。删除传递给 printf 的所有参数和传递给 scanf 的字符串的 &。也正如其他人所说,使用 %f 作为浮点数或将 age 更改为 int.

首先,在person的声明中将string改为char

struct person
{
    int age;
    char name[20], dob[20], pob[20], gender[7];
//  ^^^^
};

然后您需要在对 printf 的调用中从 &person[0].age 中删除 & 符号,因为您传递的是 int 的地址,而不是它的值。还要从 scanfprintf 调用中的字符串中删除 & 符号:

scanf("%s %s %s %s %d", person[0].name, person[0].dob, person[0].pob, person[0].gender, &person[0].age);
// Only one ampersand is needed above: -------------------------------------------------^
printf("%s %s %s %s %d", person[0].name, person[0].dob, person[0].pob, person[0].gender, person[0].age);

Demo.

你这里有一个错误:

printf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);

应该是:

printf("%s %s %s %s %d", person[0].name, person[0].dob, person[0].pob, person[0].gender, person[0].age);

因为,当您在 printf 函数中使用“&”时,您打印的是变量的地址,而不是他的值。所以请记住,您只需使用“&”来扫描任何内容,而不是打印。

年龄奇数的原因是你输出的是person[0].age的地址,而不是value。 printf() 取值,scanf() 取地址。您也可能意味着 char* 数组而不是字符串对象。下面的代码编译(虽然有一些合理的警告),并打印正确的输出(测试):

#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <sstream>

using namespace std;

struct person
{
    int age;
    char name[20], dob[20], pob[20], gender[7];
};

int main ()
{
    person person[10];
    cout << "Please enter your name, date of birth, place of birth, gender, and age, separated by a space.\nFor example, John 1/15/1994 Maine Male 20: ";
    scanf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
    printf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, person[0].age);
    return 0;
}