How to print structure contents using for-loop? If pointers, how to assign pointer to structure? I have attached code that I made that makes a structure using data that user inputs, and prints them out in an orderly fashion. My problem is that you have to write a lot of printf() and gets_s() statements to receive and print input. I feel like it would be easier to do this using a for-loop. I tried to make a for-loop as you can see in the code using pointers, but it doesn't compile, and I'm pretty sure that it is the wrong way to assign pointers to structures.
TL;DR: How to print structure contents using for-loop? If pointers, how to assign pointer to structure?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#define maxName 50
#define maxNation 50
#define maxAge 100
struct astronaut
{
char firstName[maxName];
char lastName[maxName];
char nation[maxNation];
int age = 0;
char missionName[maxAge];
int missionYear[50];
};
int main()
{
int i = 0;
struct astronaut candidate1;
struct astronaut candidate2;
struct astronaut candidate3;
struct astronaut mission1;
struct astronaut mission2;
struct astronaut mission3;
printf("Please enter the first name of the candidate: ");
gets_s(candidate1.firstName);
printf("Please enter the last name of the candidate: ");
gets_s(candidate1.lastName);
printf("Please enter the nationality of the candidate: ");
gets_s(candidate1.nation);
printf("Please enter the age of the candidate: ");
scanf("%d", &candidate1.age);
printf("Please enter the first name of the candidate: ");
gets_s(candidate2.firstName);
printf("Please enter the last name of the candidate: ");
gets_s(candidate2.lastName);
printf("Please enter the nationality of the candidate: ");
gets_s(candidate2.nation);
printf("Please enter the age of the candidate: ");
scanf("%d", &candidate2.age);
printf("Please enter the first name of the candidate: ");
gets_s(candidate3.firstName);
printf("Please enter the last name of the candidate: ");
gets_s(candidate3.lastName);
printf("Please enter the nationality of the candidate: ");
gets_s(candidate3.nation);
printf("Please enter the age of the candidate: ");
scanf("%d", &candidate3.age);
printf("Enter a Mission Name: ");
gets_s(mission1.missionName);
printf("Enter the year the mission was conducted: ");
scanf("%d", &mission1.missionYear);
printf("Enter a Mission Name: ");
gets_s(mission2.missionName);
printf("Enter the year the mission was conducted: ");
scanf("%d", &mission2.missionYear);
printf("Enter a Mission Name: ");
gets_s(mission3.missionName);
printf("Enter the year the mission was conducted: ");
scanf("%d", &mission3.missionYear);
struct astronaut *ptr;
struct candidate *ptr;
// printf("\n\tAstronaut Candidate Database\n");
// printf("Name: %s %s \t Age: %d \t Nationality: %s\n", candidate1.firstName, candidate1.lastName, candidate1.age, candidate1.nation);
// printf("Name: %s %s \t Age: %d \t Nationality: %s\n", candidate2.firstName, candidate2.lastName, candidate2.age, candidate2.nation);
// printf("Name: %s %s \t Age: %d \t Nationality: %s\n", candidate3.firstName, candidate3.lastName, candidate3.age, candidate3.nation);
// printf("\n\tAstronaut Mission Database\n");
// printf("Mission Name: %s \t Year: %d\n", mission1.missionName, mission1.missionYear);
// printf("Mission Name: %s \t Year: %d\n", mission2.missionName, mission2.missionYear);
// printf("Mission Name: %s \t Year: %d\n", mission3.missionName, mission3.missionYear);
for (int index = 0; index < 5; index++)
{
printf("Name: %s %s \t Age: %d \t Nationality: %s\n", *ptr.firstName, *ptr.lastName, *ptr.age, *ptr.nation);
ptr++;
}
_getch();
return 0;
}
I think you need 2 structs. An astronaut and a mission aren't the same thing. As it is now, you have several unused fields depending on whether you're entering data for an astronaut or a mission. You could do something like this:
#include <stdio.h>
#define maxName 50
#define maxNation 50
#define maxAge 100
struct astronaut
{
char firstName[maxName];
char lastName[maxName];
char nation[maxNation];
int age;
};
struct mission
{
char missionName[maxAge];
int missionYear; // why do you have an array of 50 ints for the missionYear?
};
void enter_candidate_data(struct candidate* cand)
{
// not famliar with gets_s .. I would use fgets here, you can read the manpage on that if you desire
printf("Please enter the first name of the candidate: ");
gets_s(cand->firstName);
printf("Please enter the last name of the candidate: ");
gets_s(cand->lastName);
printf("Please enter the nationality of the candidate: ");
gets_s(cand->nation);
printf("Please enter the age of the candidate: ");
scanf("%d", &(cand->age));
}
void enter_mission_data(struct mission* mis)
{
printf("Enter a Mission Name: ");
gets_s(mis->missionName);
printf("Enter the year the mission was conducted: ");
scanf("%d", &(mis->missionYear));
}
int main()
{
int i;
struct astronaut candidates[3];
struct mission missions[3];
for (i=0; i<3; i++)
{
enter_candidate_data(&(candidates[i]));
// you can put this in a separate loop if you want to enter all
// candidate data first
enter_mission_data(&(missions[i]));
}
// you could also write functions to print the data instead, depends on
// how you want it all presented
for (int i=0; i<3; i++)
{
printf("Name: %s %s \t Age: %d \t Nationality: %s\n",
candidates[i].firstName, candidates[i].lastName, candidates[i].nation);
printf("Mission Name: %s, year %d\n", missions[i].missionName,
missions[i].missionYear);
}
return 0;
}
You may want a number of missions (or even just one) associated with a particular astronaut. If so, I would define the data structures like this
#define MAX_ASTRONAUT_MISSIONS 20
struct mission
{
char missionName[maxAge];
int missionYear;
};
struct astronaut
{
char firstName[maxName];
char lastName[maxName];
char nation[maxNation];
int age;
struct mission missions[MAX_ASTRONAUT_MISSIONS];
};
This will allow you to associate MAX_ASTRONAUT_MISSION missions with each astronaut. Or, more realistically, a single mission could be associated with several astronauts. In that case, you may want data structures more like this
struct mission
{
char missionName[maxAge];
int missionYear;
};
struct astronaut
{
char firstName[maxName];
char lastName[maxName];
char nation[maxNation];
int age;
// using a pointer to missions will allow you to create one mission, and
// all the astronauts on that mission could get a pointer to it,
// designating they were all on that singular mission.
struct mission* missions[MAX_ASTRONAUT_MISSIONS];
};
Related
I am trying to build a program which takes user input of employee details and prints it. I have separate functions for both of them.
Structure is as follows:
struct employee
{
int empId;
char name[20];
char empType[10];
int dd, mm, yyyy;
};
struct employee input()
{
struct employee e;
printf("Enter Employee ID: \n");
scanf("%d", &e.empId);
printf("Enter Employee name: \n");
scanf("%s", &e.name);
printf("Enter employee type: \n");
scanf("%s", &e.empType);
printf("Enter joining date: \n");
scanf("%d/%d/%d", &e.dd, &e.mm, &e.yyyy);
}
void display(struct employee emp[], int n)
{
printf("Employee ID \t Name \t Employee Type \t Joining date\n");
int i;
for (i = 0; i < n; i++)
{
printf("%d %s %s %d/%d/%d", emp[i].empId, emp[i].name, emp[i].empType, emp[i].dd, emp[i].mm, emp[i].yyyy);
}
}
int main()
{
int n = 5;
struct employee emp[n];
int i;
for(i = 0; i < n ;i++)
{
emp[i] = input();
}
display(emp, n);
return 0;
}
I am able to take the input properly but while printing I am getting all values as 0.
Requesting help!
Thanks!
You forgot about the return statement in the function input
//...
return e;
Also the arguments of these calls of scanf
printf("Enter Employee name: \n");
scanf("%s", &e.name);
printf("Enter employee type: \n");
scanf("%s", &e.empType);
are incorrect. You need to write
printf("Enter Employee name: \n");
scanf("%19s", e.name);
printf("Enter employee type: \n");
scanf("%9s", e.empType);
In general you should check that inputs were successful.
That for loop is unneccessary - you would end up printing the output 5 times, for some reason.
Also use typedef struct, it's convenient.
And don't type & when dealing with struct's string elements.
This code is a mess, by the way.
I'm practicing C using structs and pointers, I'm asking to the user to input some info using structs and then using pointers to modify it but I'm having problems when I need to get a string with spaces. I switched all the scanfs for fgets and still getting problems with the output.
#include <stdio.h>
#include <stdlib.h>
#define MAXTSTR 25
int main(int argc, char **argv) {
typedef struct birthday {
int day, year;
char month[10];
} BDATE;
struct employee {
char name[MAXTSTR];
int id;
float salary;
BDATE bday;
} emp;
struct employee *ptrEmp = &emp;
printf("Enter employee name:");
fgets(emp.name, MAXTSTR, stdin );
printf("enter id number:");
scanf(" %d", &emp.id);
printf("enter salary");
scanf(" %f", &emp.salary);
printf("enter birhday:");
scanf(" %d", &emp.bday.day);
printf("enter year:");
scanf(" %d", &emp.bday.year);
printf("enter month:");
fgets(emp.bday.month, MAXTSTR, stdin);
printf("\nName: %s \nID: %d \nSalary: %.2f\n", emp.name, emp.id, emp.salary);
printf("%d %s %d", emp.bday.day, emp.bday.month, emp.bday.year);
printf("\n------------------------------------\n");
printf("Enter employee name:");
fgets(ptrEmp->name, MAXTSTR, stdin);
printf("enter id number:");
scanf(" %d", &ptrEmp->id);
printf("enter salary");
scanf(" %f", &ptrEmp->salary);
printf("enter birhday:");
scanf(" %d", &ptrEmp->bday.day);
printf("enter year:");
scanf(" %d", &ptrEmp->bday.year);
printf("enter month:");
scanf(ptrEmp->bday.month, MAXTSTR, stdin);
printf("\nName: %s \nID: %d \nSalary: %.2f\n",
ptrEmp->name, ptrEmp->id, ptrEmp->salary);
printf("%d %s %d", ptrEmp->bday.day, ptrEmp->bday.month,
ptrEmp->bday.year);
return (EXIT_SUCCESS);
}
INPUT and OUTPUT EXAMPLE
Enter employee name:Luis Oliveira
enter id number:01
enter salary1525.25
enter birhday:05
enter year:1991
enter month:
Name: Luis Oliveira
ID: 1
Salary: 1525.25
5
1991
------------------------------------
Enter employee name:Patricia Santos
enter id number:02
enter salary16546.46
enter birhday:05
enter year:1946
enter month:Fev
Name: Patricia Santos
ID: 2
Salary: 16546.46
5
1946
What I'm doing wrong?
Thank you in advance for your help.
Mixing scanf() and fgets() can be very confusing: scanf() leaves the pending newline in the input stream and fgets() reads it and immediately returns because it has reached the end of line.
You can read the month with scanf("%9s", emp.bday.month); and the employee name with scanf(" %14[^\n]", ptrEmp->name);.
Also check for invalid input causing scanf() to return a value different from the expected 1.
Modified program:
#include <stdio.h>
#include <stdlib.h>
#define MAXTSTR 25
typedef struct birthday {
int day, year;
char month[10];
} BDATE;
struct employee {
char name[MAXTSTR];
int id;
float salary;
BDATE bday;
};
int main(int argc, char **argv) {
struct employee emp;
for (int i = 0; i < 2; i++) {
printf("Enter employee name: ");
if (scanf(" %14[^\n]", emp.name) != 1)
return EXIT_FAILURE;
printf("enter id number: ");
if (scanf(" %d", &emp.id) != 1)
return EXIT_FAILURE;
printf("enter salary: ");
if (scanf(" %f", &emp.salary) != 1)
return EXIT_FAILURE;
printf("enter birthday: ");
if (scanf(" %d", &emp.bday.day) != 1)
return EXIT_FAILURE;
printf("enter year: ");
if (scanf(" %d", &emp.bday.year) != 1)
return EXIT_FAILURE;
printf("enter month: ");
if (scanf("%9s", emp.bday.month) != 1)
return EXIT_FAILURE;
printf("\n\nName: %s\nID: %d\nSalary: %.2f\n", emp.name, emp.id, emp.salary);
printf("Birthday: %d %s %d\n", emp.bday.day, emp.bday.month, emp.bday.year);
printf("\n------------------------------------\n");
}
return EXIT_SUCCESS;
}
So I'm trying to write a program in which I need to enter informations like name, surname, student id, birthday for multiple students . The thing is I can't get it to print the info for all the students. This version of the code I wrote just prints the variables without anything stored in them or with some weird characters. In an earlier version of the script the info I typed in would just overwrite the previous info and it would print just one student's info. I think I need to make some changes in the for loop if I'm not mistaken. If someone could give me a hand, I'd appreciate it.
Here's the code:
#include <stdio.h>
#include <string.h>
#define students 200
typedef struct {
char name[20];
char surname[20];
int studentid[5];
int day[5];
int month[5];
int year[5];
}student;
int main(){
student a[students];
int j;
int n;
int i;
int choice;
for(i=0;i<=students;i++){
printf("\n===========================================================\n");
printf("\n1 Enter info for a student");
printf("\n2 Print all the students");
printf("\n3 End\n");
printf("\n===========================================================\n");
printf("\nChoose something ---> ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter name: \n");
scanf("%s", a[students].name);
printf("Enter surname: \n");
scanf("%s", a[students].surname);
printf("Enter student ID: \n");
scanf("%s", a[students].studentid);
printf("Enter day: \n");
scanf("%s", a[students].day);
printf("Enter month: \n");
scanf("%s", a[students].month);
printf("Enter year: \n");
scanf("%s", a[students].year);
break;
case 2:
for(i=0;i<students;i++)
{
printf("\nNome student: %s\nSurname student: %s\nStudent id: %s\nStudent Birthday: %s.%s.%s\n", a[i].name, a[i].surname, a[i].studentid, a[i].day, a[i].month, a[i].year);
}
break;
case 3:
break;
default:
printf("Choose again!\n");
}
}
return 0;
}
Thanks!
Did you see the warning when you compile:
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int *’ [-Wformat=]
For string, you should use the character array, so the parameters of the struct student should change to:
char studentid[10];
char day[10]; // 5 is too short, for example monday need at lest 7 characters (1 for null character at the end of string)
char month[10];
char year[10];
You declare the array with length = students but you try to access the (students+1)th (a[students])
The for loop should change to:
for(i=0;i < students;i++){} // i from 0 to students-1 not to students.
You should use the counter (you can declare the variable count for example) to count the number of students that you enter the info. It will be useful when you print the info of these students.
printf("Enter name: \n");
scanf(" %19s", a[count].name);
printf("Enter surname: \n");
scanf(" %19s", a[count].surname);
printf("Enter student ID: \n");
scanf(" %9s", a[count].studentid);
printf("Enter day: \n");
scanf(" %9s", a[count].day);
printf("Enter month: \n");
scanf(" %9s", a[count].month);
printf("Enter year: \n");
scanf(" %9s", a[count].year);
count++; // increase count after each student
break;
case 2 changes to:
for(int j=0;j<count;j++) // just print the students that you set the info in case 1.
{
printf("\nNome student: %s\nSurname student: %s\nStudent id: %s\nStudent Birthday: %s.%s.%s\n", a[j].name, a[j].surname, a[j].studentid, a[j].day, a[j].month, a[j].year);
}
break;
This line: #define students 200 is not wrong, but you should use the difference name and use the uppercase, it's easier to understand the constant value, for example:
#define MAX_NUM_STUDENTS 200
The complete code:
#include <stdio.h>
#include <string.h>
#define MAX_NUM_STUDENTS 200
typedef struct {
char name[20];
char surname[20];
char studentid[10];
char day[10];
char month[10];
char year[10];
}student;
int main(){
student a[MAX_NUM_STUDENTS];
int i, n, choice, count = 0;
for(i=0;i<MAX_NUM_STUDENTS;i++){
printf("\n===========================================================\n");
printf("\n1 Enter info for a student");
printf("\n2 Print all the students");
printf("\n3 End\n");
printf("\n===========================================================\n");
printf("\nChoose something ---> ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter name: \n");
scanf(" %19s", a[count].name);
printf("Enter surname: \n");
scanf(" %19s", a[count].surname);
printf("Enter student ID: \n");
scanf(" %9s", a[count].studentid);
printf("Enter day: \n");
scanf(" %9s", a[count].day);
printf("Enter month: \n");
scanf(" %9s", a[count].month);
printf("Enter year: \n");
scanf(" %9s", a[count].year);
count++;
break;
case 2:
for(int j=0;j<count;j++) // just print the students that you set the info in case 1.
{
printf("\nNome student: %s\nSurname student: %s\nStudent id: %s\nStudent Birthday: %s.%s.%s\n", a[j].name, a[j].surname, a[j].studentid, a[j].day, a[j].month, a[j].year);
}
break;
case 3:
break;
default:
printf("Choose again!\n");
}
}
return 0;
}
You're storing the user input at a[students]. However, the array a (by the way, you should be descriptive with your variable names) is only students-elements long. Therefore, the students-th element is past the end of the array.
I have this project where I have to create a struct array with C language for students' data, and I can't seem to get past this warning by my variable arr_student. The warning says that I have not initialized the variable, and whenever I try to debug it the IDE says that it has a memory error involving where it goes. I want to be able to declare it and use it as a way to get to the variables created in my struct array. If anyone knows what I could be missing, that would be greatly appreciated!
#include <stdio.h>
#include <string.h>
#define numero 2 //This number is the limiter for the number of students
struct Student
{ //Define struct array with student information
char id[50];
char gpa[50];
char address[50];
char phone_number[50];
char first_name[50];
char last_name[50];
};
int main(struct Student arr_student[numero])
{
int i; //Counter
char tempvalue[50]; //Temporary variable to store data in the array
char search[50]; //Search value input by user
int result = 1; //Initialized result to false
for (i = 0; i < numero; i++)
{
//Asks user for input on student information.
printf("\nEnter the information for student %d\n\n", i + 1);
printf("\nEnter first name: ");
scanf("%s", tempvalue);
printf("%s", tempvalue);
//prints value to verify if tempvalue recieved
strcpy(arr_student[i].first_name, tempvalue);
//error begins with the arr_student being underlined
printf("\nEnter last name: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].last_name, tempvalue);
printf("\nEnter student id: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].id, tempvalue);
printf("\nEnter student gpa: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].gpa, tempvalue);
printf("\nEnter student address: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].address, tempvalue);
printf("\nEnter student phone number: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].phone_number, tempvalue);
}
printf("Enter the last name of the student you wish to examine data for: ");
//Asks input from the user for a name to search the data for
scanf("%s", search);
for (i = 0; i < numero; i++)
{
result = strcmp(search, arr_student[i].last_name);
}
if (result == 0) //A match is found in the array
{
printf("Here is the data on the student: %s", search);
printf("First Name\t Last Name\t ID\t GPA\t Address\t Phone Number\n");
//Prints out student information
printf("%s\t%s\t%s\t%s\t%s\t%s\n",
arr_student[i].first_name, arr_student[i].last_name, arr_student[i].id,
arr_student[i].gpa, arr_student[i].address, arr_student[i].phone_number);
}
else
{
printf("The name you have entered is not in our system, please try again");
return;
}
return 0;
}
Change the invalid main() definition from
int main(struct Student arr_student[numero])
{
to
int main(void) {
struct Student arr_student[numero] = {0};
Use width limited input.
char tempvalue[50];
// scanf("%s", tempvalue);
scanf("%49s", tempvalue);
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 years ago.
I wrote this C program to enter names and ages of 3 people. But the output wasn't my expectation. It was able to enter name and age for the first person, but it wasn't able for second and third persons. Please help.
#include <stdio.h>
#include <string.h>
int main()
{
int i, age;
char name[20];
for(i=0; i<3; i++)
{
printf("\nEnter name: ");
gets(name);
printf("Enter age: ");
scanf(" %d", &age);
puts(name);
printf(" %d", age);
}
return 0;
}
In short: Your 2nd puts is processing the '\n' from your scanf.
Fix by adding getchar(); after scanf
Explanation:
1st iteration:
printf("\nEnter name: ");
gets(name); // line is read from input
printf("Enter age: ");
scanf(" %d", &age); // a number is read from input, and the newline char ('\n') remains in buffer
puts(name);
printf(" %d", age);
2nd iteration:
printf("\nEnter name: ");
gets(name); // previously buffered newline char is read, thus "skipping" user input
printf("Enter age: ");
scanf(" %d", &age);
puts(name);
printf(" %d", age);
Same goes for 3rd iteration, and this is why you lose user input
The best way to store information of more than one person is to use struct, like
struct person {
int age;
char name[20];
};
and make array of struct, like
struct person people[3];
than use loop with accessing people[i].age and people[i].name, e.g.:
#include <stdio.h>
#include <string.h>
struct person {
int age;
char name[20];
};
#define ARR_SIZE 3
int main(int argc, char* argv[])
{
struct person people[ARR_SIZE];
int i;
char *lastpos;
for(i = 0; i < ARR_SIZE; i++)
{
printf("\nEnter name: ");
scanf(" %s", people[i].name);
if ((lastpos=strchr(people[i].name, '\n')) != NULL) *lastpos = '\0'; // remove newline from the end
printf("Enter age: ");
scanf(" %d", &people[i].age);
}
printf("This is the people you entered:\n");
for(i = 0; i < ARR_SIZE; i++)
{
printf("%d : %s : %d\n", i+1, people[i].name, people[i].age);
}
return 0;
}
UPDATE:
As you see I use scanf(" %s", people[i].name); instead of gets(people[i].name); to read name from stdin. Try both option for the following cases:
enter short name (e.g. John) and correct age (e.g. 15)
enter two word name (e.g. John Smith) and correct age (e.g. 17)
enter short name and uncorrect age (e.g. five)
Then read articles about value returned by scanf and cleaning input buffer