Mouse
Mouse

Reputation: 29

Reading in and recording a number in C

This is a homework problem. I have a C program that takes user input for a number of people's first names, last names, and ages. Right now it works and prints out the names to the console correctly, but it is not printing out the right ages, and I can't figure out what I'm doing wrong. Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int choice;
    int i = 0;
    int x,k,l;
    fputs("How many people would you like to add? ", stdout);
    scanf(" %d", &choice);
    fflush(stdout);

    int ch;
    while((ch = getchar()) != EOF && ch != '\n');
    if (ch == EOF) 
    {
    }

    char firstName[choice][20];
    char lastName[choice][20];
    int age[choice][3];

    char first[20];
    char last[20];
    int a[3];

    for (x = 0; x < choice; x++) 
    {
        for (l = 0; l < 3; l++)
        {
            age[x][l] = 0;
            a[l] = 0;
        }
    }


    while(i < choice)
    {
      printf("Enter the first name of person ");
      printf(" %d", i);
      printf(": ");
      fgets(first, 20, stdin); 

      for (k = 0; k < 20; k++)
      { 
        firstName[i][k] = first[k];
      }
      i++;
    } 

    i = 0;
    while(i < choice)
    {
      printf("Enter the last name of person ");
      printf(" %d", i);
      printf(": ");
      fgets(last, 20, stdin);     

      for (k = 0; k < 20; k++)
      { 
          lastName[i][k] = last[k];
      }
      i++;
    } 

    i = 0;

    while(i < choice)
    {
      fputs("Enter the age of person ", stdout);
      printf(" %d", i);
      printf(": ");
      scanf(" %d", &a);
      fflush(stdout);

      for (l = 0; l < 3; l++)
      { 
          age[i][l] = a[l];
      }
      i++;
    }

    int sh;
    while((sh = getchar()) != EOF && sh != '\n');
    if (sh == EOF) 
    {
    }

    for (x = 0; x < choice; x++) 
    {
      printf("First name ");
      printf(": ");
      printf("%s ", firstName[x]);
      printf("\n");
      printf("Last name ");
      printf(": ");
      printf("%s ", lastName[x]);
      printf("\n");
      printf("Age ");
      printf(": ");
      printf("%d ", &age[x]);
      printf("\n");
    }
    return 0;
}

If you copy/paste this code it will run, but the age outputted will be incorrect. Can anyone tell me why this is? Thank you!

Upvotes: 0

Views: 109

Answers (1)

David Schwartz
David Schwartz

Reputation: 182761

scanf(" %d", &a);

That should be:

scanf(" %d", &a[0]);

And the printf should be printf("%d", age[x][0]);

You want to read into the first element of the array, not the entire array. You want to print out the first element of the array, not the address of the array.

A better solution would probably be not to make age an array of 3 at all. Each person only has one age. The changes would be:

int age[choice];

int a;

scanf(" %d", &a);

age[choice] = a;

printf("%d ", age[x]);

Upvotes: 2

Related Questions