I'm currently trying to create a program from a struct function as I show below. Instead of printing a line directly from the program, I want to modify the program to print a message asking the user to input the information about a person and display it as the struct indicates.
Instead of doing "struct person p" and inserting the information, i want it to be inputed as a scanf.
#include <stdio.h>
typedef struct {
int day, month, year;
} DATA;
typedef struct person {
char name[100];
int age;
float salary;
DATA birth;
} PERSON;
void Mostrar(struct person x){
printf("name: %s\n",x.name);
printf("age: %d\n",x.age);
printf("Salário: %f\n",x.salary);
printf("Dt.birth: %d/%d/%d\n",x.birth.day, x.birth.month, x.birth.year);
}
int main(){
struct person p = {"Carlos", 23, 12345, {23,5,1954}};
Mostrar(p);
}
Thanks for the help guys!
Simply use scanf
PERSON getPerson(void)
{
PERSON person;
if(!fgets(person.name, sizeof(person.name), stdin)) { /* error handling */} //you can also remove \n at the end if you need to
if(scanf("%d %f", &person.age, &person.salary) != 2) { /* error handling */}
if(scanf("%d %d %d", &person.birth.day, &person.birth.month, &person.birth.year) != 3) { /* error handling */}
return person;
}
Related
I have two structures. A pointer is assigned to one.
Now I would like to output data previously entered via scanf via a function (outputAddress) with a pointer as a parameter.
It works with the variables via the pointer. But how do I do that with the values from the other structure? How can I output this in the function?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct structPerson
{
char name[30];
char forename[50];
int age;
};
struct structAddress
{
int zip;
char location[35];
char street[40];
int hNumber;
struct structPerson *ptrPerson;
};
void outputAddress(struct structPerson *ptrPerson)
{
printf("\n\nOutput Address: \n");
printf("ptrPerson->name: %s", ptrPerson->name);
printf("\nptrPerson->forename: %s", ptrPerson->forename);
return;
}
int main()
{
struct structPerson person1;
struct structAddress address1;
address1.ptrPerson = &person1;
printf("Location: ");
scanf("%s", &address1.location);
printf("Zip: ");
scanf("%d", &address1.zip);
printf("\nName: ");
scanf("%s", &address1.ptrPerson->name);
printf("Forename: ");
scanf("%s", &address1.ptrPerson->forename);
printf("\nOutput: %d %s %s\n", address1.zip, address1.location, address1.ptrPerson->name);
// strcpy( address1.location, "");
// printf("structAddress1: %d %s\n", address1.zip, address1.location);
outputAddress(&person1);
return 0;
}
In your data model structAddress is associated with a person via the personPtr field. As a result, Address is a main data struct. If I understand your intention correctly, you want to print info about the person and then his/her address.
For this you need to do a couple of changes. Firstly, you should pass the Address struct to the print function, because it has all information available, including the pointer to the person. Secondly, you should access your person information using the pointer: ptrAddress->ptrPerson-><field>. Here is an example.
void outputAddress(struct structAddress *ptrAddress)
{
printf("\n\nOutput Address: \n");
// use ptrAddress->ptrPreson to accesss person information
printf("ptrPerson->name: %s", ptrAddress->ptrPerson->name);
printf("\nptrPerson->forename: %s", ptrAddress->ptrPerson->forename);
// use ptrAddress-> to access address fields.
printf("\nptrAddress->zip: %d", ptrAddress->zip);
...
return;
}
int main() {
...
outputAddress(&address1); // << use address1 here.
...
}
Your datamodel is probably broken anyway. The address struct has a pointer to a person, but it often makes more sense to have it the other way around.
Fields of Student: name, lastName, studentId, mid1Grade, mid2Grade, finalGrade, average
Fields of Course: courseName, courseCode, myStudentArray (array of Student structures),currentStudentCount
Functions:
void createNewStudent(struct Course *myCourse);
void setGradeOfStudent(struct Course *myCourse);
void findAndDisplayAverage(struct Course *myCourse);
struct Student * findStudentByID(int id, struct Course *myCourse);
void displayAverageOfAllStudents(struct Course *myCourse);
void displayAverageOfStudentsInInterval(struct Course *myCourse
ok so I have written the first function but there is an error which I dont understand. First of all the first function and what it does:
createNewStudent: Prompt the user to enter name, last name and id of the new student.Values entered by the user are assigned to the fields of the student residing in themyStudentArray of course variable pointed by myCourse. currentStudentCount will be updated so that it designates the slot allocated for the student inserted next.
and my implementation:
#include <string.h>
#include <stdio.h>
struct Student {
char name[50];
char lastname[50];
int id;
int mid1;
int mid2;
int final;
double average;
};
struct Course {
char courseName[50];
char courseCode[50];
struct Student myStudentArray[5];
int currentstudentcount;
};
void createNewStudent(struct Course * myCourse);
void setGradeOfStudent(struct Course * myCourse);
void findAndDisplayAverage(struct Course * myCourse);
struct Student * findStudentByID(int id, struct Course * myCourse);
void displayAverageOfAllStudents(struct Course * myCourse);
void displayAverageOfStudentsInInterval(struct Course * myCourse);
int main() {
struct Student * stud;
int input = 0;
scanf("%d", & input);
if (input == 1) {
createNewStudent(struct Course * myCourse);
}
}
return 0;
}
void createNewStudent(struct Course * myCourse) {
struct Student s1;
printf("Enter name: ");
scanf("%[^\n]%*c", s1.name);
printf("Enter Surname: ");
scanf("%[^\n]%*c", s1.lastname);
printf("Enter id: ");
scanf("%d", & s1.id);
}
When you call the function with the if(input == 1) it gives
error: expected expression before ‘struct’
but I dont understand this beacuse *myCourse is just a pointer to the Course struct isn't it ????
If I can understand this ı will be able to the the next functions I think
Is the function correct ?? I dont know why this doesnt work
Ok I tried to use the struct Student myStudentArray[5]; to get name, lastname,id like so (structs are the same)
void createNewStudent(struct Course *myCourse);
void setGradeOfStudent(struct Course *myCourse);
int main(){
struct Course *myCourse;
int input=0;
scanf("%d",&input);
if(input == 1){
createNewStudent(myCourse);
}
return 0;
}
void createNewStudent(struct Course *myCourse){
myCourse->currentstudentcount=0;
printf("Enter name: ");
scanf("%[^\n]%*c"
,myCourse->myStudentArray[myCourse->currentstudentcount].name);
printf("Enter Surname: ");
scanf ("%[^\n]%*c",
myCourse->myStudentArray[myCourse->currentstudentcount].name);
myCourse->currentstudentcount++;
}
I Keep getting
may be used uninitialized in this may be used uninitialized in this function [-Wmaybe-uninitialized]
and
Segmentation errors
void createNewStudent(struct Course * myCourse)
If you want to create new student, you should use the student struct as the parameter of this function instead of using struct Course.
void createNewStudent(struct Student *s1)
Then, this function becomes as:
void createNewStudent(struct Student *s1) {
printf("Enter name: ");
scanf("%49s", s1->name);
printf("Enter Surname: ");
scanf("%49s", s1->lastname);
printf("Enter id: ");
scanf("%d", & s1->id);
}
If you want to test, in main function, you can declare the value stud or the pointer to struct Student.
For example:
int main() {
struct Student stud;
int input = 0;
scanf("%d", & input);
if (input == 1) {
createNewStudent(&stud);
printf("name: %s\n Surname: %s\n id = %d\n", stud.name, stud.lastname, stud.id);
}
return 0;
}
The complete program for test:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct Student {
char name[50];
char lastname[50];
int id;
int mid1;
int mid2;
int final;
double average;
};
struct Course {
char courseName[50];
char courseCode[50];
struct Student myStudentArray[5];
int currentstudentcount;
};
void createNewStudent(struct Student *s1);
int main() {
struct Student stud;
int input = 0;
scanf("%d", & input);
if (input == 1) {
createNewStudent(&stud);
printf("name: %s\nSurname: %s\nid = %d\n", stud.name, stud.lastname, stud.id);
}
return 0;
}
void createNewStudent(struct Student *s1) {
printf("Enter name: ");
scanf("%49s", s1->name);
printf("Enter Surname: ");
scanf("%49s", s1->lastname);
printf("Enter id: ");
scanf("%d", & s1->id);
}
The output:
#./test
1
Enter name: abc
Enter Surname: def
Enter id: 100
name: abc
Surname: def
id = 100
Update for your question in the comment:
If you want to store student info in an array, you can change the code to:
struct Student myStudentArray[5];
int input = 0;
scanf("%d", & input);
if (input == 1) {
for (int i = 0; i < 5; i++) {
createNewStudent(&myStudentArray[i]);
}
for (int i = 0; i < 5; i++) {
printf("name: %s\nSurname: %s\nid = %d\n", myStudentArray[i].name, myStudentArray[i].lastname, myStudentArray[i].id);
}
}
For Course structure you can create one function as the function createNewStudent but for struct Course to create the new course. After creating new 5 students (for example the code above), you can copy the myStudentArray to new_course.myStudentArray. Then now you have the info of 5 students in new_course. When you copy value from an array to another, you can use memcpy or using one loop to copy each element from one array to another one. Do not use something like myStudentArray = new_course.myStudentArray for the array.
You are making a declaration as a parameter of the createNewStudent() function. In C, functions require expressions as parameters, which is why you got the error message "expected expression...".
So, just create the struct pointer before you call the function:
if (input == 1) {
struct Course *myCourse = malloc(sizeof(struct Course));
createNewStudent(myCourse);
}
Notice the use of malloc(), which returns a pointer to a place in memory of sufficient size to hold that particular Course struct. When dealing with pointers to structs, you need to allocate memory for the structs that will ultimately be pointed to, in order to avoid dereferencing unallocated regions of memory.
In your function CerateNewStudent, the proper way to address the variables into which to place the data read by scanf should be:
myCourse->myStudentArray[myCourse->currentstudentcount].name
as the variable to read name into. Use this syntax for all data items to read. After that, increment the counter:
myCourse->currentstudentcount++;
Note: what is missing in all your functions (and in the assignment?) is a way to create a course. The students created are all added to courses. First a course should be created and then students can be added to it.
#include <stdio.h>
int j=0;
struct student
{
int CNE;
char Nom[20];
char Prenom[20];
char Ville[20];
float Note[3];
float Moyenne;
};
void read_struct(struct student stu)
{
stu.Moyenne=0;
printf("Nom de l'etudiant:\t ");
scanf(" %s",stu.Nom);
printf("Prenom de l'etudiant:\t ");
scanf(" %s",stu.Prenom);
printf("CNE de l'etudiant:\t ");
scanf("%d",&stu.CNE);
}
int main()
{
struct student stu[10];
read_struct(stu[0]);
read_struct(stu[1]);
printf("%s \n %s \n",stu[0].Nom,stu[1].Nom);
printf("%d \n %d",stu[0].CNE,stu[1].CNE);
}
I m getting some weird output after compiling, the input from users are not saved in struct after calling them back.( sorry for my english)
Look at how this function is defined:
void read_struct(struct student stu) {
...
}
When you call this function, it passes in a copy of the struct student, so the function does its work to fill in the copy rather than the original.
You may want to have this function take in a pointer to the struct student:
void read_struct(struct student* stu) {
/* You'll need to change things here */
}
read_student(&stu[0]);
read_student(&stu[1]);
Hope this helps!
I'm just starting to learn C in one of my college courses. We have gone over similar topics but not quite like what my professor is asking. I'm not great at all with pointers or structs so this assignment is getting frustrating, but I'm getting only one error in my last scanf saying "expected type char* but getting struct user**" and I cannot figure it out.
#include <stdio.h>
#define PEOPLE 10
struct user {
int user_id;
char* user_name;
};
void populate(struct user* users, int size);
void main() {
struct user s1[PEOPLE], s2;
populate(&s2, s1->user_id);
}
void populate(struct user* users, int size) {
for(int i = 1; i < PEOPLE + 1; i++) {
printf("Enter an ID of user %d: ", i);
scanf("%d", &size);
printf("Enter the name of user %d: ", i);
scanf("%s", users);
}
}
Here is the assignment:
Write a C programs that do the following:
Program defines a C struct, called user, that has two attributes
int user_id;
char* user_name;
Program declares an array of about 10 struct user variables and a function called populate() that takes as parameters a pointer to a struct user variable and an integer size. The populate() method will ask the user for an id and name to be assigned to each cell in the array of struct user variables until the array is full.
Hint: A header for this function might look like void populate (struct user* users, int size);
Here is the error message:
https://i.stack.imgur.com/xLUyo.png
In your second scanf statement, you're trying to capture a string argument with a struct variable. Your second scanf statement should be the following:
scanf("%s", users-> user_name);
You're also passing the wrong arguments to your function. The complete code is as given below:
#include <stdio.h>
#define PEOPLE 10
struct user {
int user_id;
char user_name[20];
};
void populate(struct user* users, int size);
void main() {
struct user s1[PEOPLE];
populate(s1, PEOPLE);
}
void populate(struct user users[], int size) {
for(int i = 0; i < size; i++) {
printf("Enter an ID of user %d: ", i+1);
scanf("%d", &users[i].user_id);
printf("Enter the name of user %d: ", i+1);
scanf("%s", users[i].user_name);
}
}
Error after providing the input value of ID. But working when values directly assigned. Compiled Successfully.
#include<stdio.h>
#include <string.h>
typedef struct student
{
char name[20];
int id;
int mob;
} stu;
void printstudent(stu *stud);
void main()
{
stu s1;
strcpy(s1.name,"name");
printf("Enter Student id");
scanf("%d",s1.id);
//s1.id=1;
printf("Enter Student Mob no");
scanf("%d",s1.mob);
//s1.mob=9911;
printstudent(&s1);
}
void printstudent(stu *stud)
{
printf("\n%d",stud->id);
printf("\n%s",stud->name);
printf("\n%d",stud->mob);
}
Error after providing the input value of ID. But working when values directly assigned.
s1.id and s1.mob are not pointers to the int, you should use &s1.id and &s1.mob