为什么我不能扫描和打印整数?

Why can't I scanf and printf an integer?

本文关键字:打印 整数 扫描 不能 为什么      更新时间:2023-10-16
#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;
}

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

首先,在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);

演示。

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

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

另外,按照达斯布林肯莱特先生的建议,将string改为char

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

不要将它们混为一谈并期望它们起作用。如果向提供的格式说明符提供不正确类型的参数,则最终将导致未定义的行为。

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

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

你在这里有一个错误:

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 的地址,而不是值。 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;
}