Working on some self study in understanding structures in C.
I’ve made a small program that gets info from the user and then prints it back via functions.
I used two different methods of handing off the data using a couple examples in the C Primer Plus book.
What happens is that I can input the data but when it prints it back out the numeric data is ok but only the first character in each string is printed with garbage after it.
My code is below for review. I can’t figure out what the issue is.
Any help would be great. Thanks!
#include <stdio.h>
#include <stdlib.h>
struct stats {
char name;
char city;
int wins;
int losses;
int draws;
};
void screen_print(char name,char city,int wins,int losses,int draws);
void team_input (struct stats * ptr);
int main()
{
struct stats team;
team_input(&team);
screen_print(team.name,team.city,team.wins,team.losses,team.draws);
return 0;
}
void screen_print(char name,char city,int wins,int losses,int draws)
{
// system("cls");
printf("==================================================\n");
printf("Name:\t\t\t%s\n",&name);
printf("City:\t\t\t%s\n",&city);
printf("Number of Wins:\t\t%d\n",wins);
printf("Number of Losses:\t%d\n",losses);
printf("Number of Draws:\t%d\n",draws);
printf("==================================================");
}
void team_input (struct stats * ptr)
{
system("cls");
printf("Enter Team name: ");
scanf("%s",&(ptr->name));
printf("\nEnter City:");
scanf("%s",&(ptr->city));
printf("\nEnter Wins:");
scanf("%d",&(ptr->wins));
printf("\nEnter Losses:");
scanf("%d",&(ptr->losses));
printf("\nEnter Draws:");
scanf("%d",&(ptr->draws));
}
nameandcityare single characters only: they are not strings.scanf("%s",&(ptr->name));is invalid and will be overwriting memory as an attempt is being made to read a string into a singlechar.printf("%s", &name);expectsnameto be a null terminated string, so it will print thenamecharthen random characters until a null is found somewhere in memory.Change to:
or dynamically allocate memory before populating if maximum possible length of
nameandcityare unknown beforehand.Change the
printf()statements to:and
scanf()statements to:and
screen_print()signature to: