Why can not I scan and print a whole number?

advertisements
#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;
}

I try to scan and print the user's age but it gives me 2749536 for the person.age value. Why is that?


First, change string to char in the declaration of person:

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

Then you need to remove ampersand from &person[0].age in the call to printf, because you are passing an address of the int, not its value. Also remove ampersands from strings in scanf and printf calls:

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.