How to assign fields of a struct from scanning stdin? - c

I want the program to extract data from the user through the console, by scanning stdin with the scanf() and fgets() and assign the values to named structs, to eventually print them out.
Right the following code is not working. The problem is the code does not recognize the scanned input and the array corona and fails to assign it into that array at index "0".
Here's the code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
char name[100];
char phone[100];
} Person;
typedef struct {
char location[100];
char time[100];
} Event;
typedef struct {
Person person;
Event event;
} Corona;
int main() {
/*help variables*/
char* name2;
char* number2;
char* location2;
char* date2;
Corona corona[28]; //creating list with 28 objects just because. it could be 5 or x too.
printf("Name");
fgets(name2, 50, stdin); //user input for name
printf("Nummer/location/date");
scanf("%s %s %s", number2, location2, date2); //user input for phone number, location and date
corona[0]= *(Corona*)malloc(sizeof (Corona)); //allocating memory for array
corona[0]={{("%s",name2),("%s", number2)}, {("%s", location2),("%s", date2)}};
/*printing out the information of array "corona" with index 0"*/
printf("Name: %s\n", corona[0].person.name);
printf("Phone: %s\n", corona[0].person.phone);
printf("Location: %s\n", corona[0].event.location);
printf("Time: %s\n", corona[0].event.time);
return 0;
}

lets fix one part of this and see if you can fix the rest
printf("Nummer/location/date");
scanf("%s %s %s", corona[0].person.phone,
corona[0].event.location,
corona[0].event.time);
no need for any mallocs, fancy casts or whatever that assignment line is tryong to do
ie these lines
corona[0]= *(Corona*)malloc(sizeof (Corona)); //allocating memory for array
corona[0]={{("%s",name2),("%s", number2)}, {("%s", location2),("%s", date2)}};

Related

Output of values of a struct via a function with a pointer as a parameter

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.

Is this a correct usage of struct?

#include <stdio.h>
int main()
{
struct database
{
char name[10];
int number;
int roll;
};
struct database s1,s2;
printf("enter name, number , roll: ");
scanf("%c%d%d",&s1.name,&s1.number,&s1.roll);
scanf("%c%d%d",&s2.name,&s2.number,&s2.roll);
printf("Entered value is :");
printf("%c%d%d",s1.name,s1.number,s1.roll);
printf("%c%d%d",s2.name,s2.number,s2.roll);
}
I've been trying to get output but I don't know if this correct Or should I access them individually? Help would be very much appreciated! thanks :)
If you need the specific struct only within the function body, then your declaration will suffice. But, note that if you want a struct to be used throughout the program, then it needs to be defined like this:
struct database {
...
};
int main(void) {
struct database s1, s2;
...
}
Also, you're trying to accept a single char value:
scanf("%c%d%d", &name, ...);
// --^^--
Here, you are expected to get a char from the user:
scanf("%9s%d%d", name, ...);
Note: The %9s is specifically given to prevent input buffer overflow.
A nicely structured program would look like (notice comments):
#include <stdio.h>
// Don't use magical numbers for constants in the program
// The use macros for this will suffice and look a ton cleaner
#define MAX_LENGTH 64
#define FMT_LENGTH "%63s"
// Our structure
struct database {
char name[MAX_LENGTH];
int number;
int roll;
};
int main(void) {
// You are here only creating single instances of struct
struct database s1, s2;
printf("Enter name, number and roll: ");
// Always check if the values are correctly assigned to their respective
// variables, if not, print error and exit (in this context)
if (scanf(FMT_LENGTH " %d %d", s1.name, &s1.number, &s1.roll) != 3) {
printf("error: One of the values are incorrectly assigned.\n");
return 1; // Exit Failure
}
// Same with s2
printf("Name: %s | Number: %d | Roll: %d\n", s1.name, s1.number, s1.roll);
return 0;
}

Allocating memory for a struct variable using a function

As part of a larger project, I am trying to write a function that will allocate enough memory for a struct variable and assign values to its member variables after scanning them from the keyboard. In other words, I am trying to create a sort of a constructor function. The reason for this is because I think that's the best way to create a database-like program in c, where all the student_t variables will be stored in a student_t* array called classroom.
#include <stdio.h>
#include <stdlib.h>
#define N 10
#define STRLIM 50
typedef struct student{
char* name;
int age;
}student_t;
student_t* init_student(student_t* s);
int i=0;//its the array counter
student_t* classroom[N];
int main(int argc, char const *argv[]){
while(i<N){
// classroom[i]=(student*)malloc(sizeof(student));
init_student(classroom[i]);
classroom[i]->age=i;
printf("The age of student #%d is : %d \n",i,classroom[i]->age);
printf("the name of student #%d is : %s",i,classroom[i]->name);
i++;
}
printf("the size of the classroom is : %ld",sizeof(classroom));
return 0;
}//end of main()
student_t* init_student(student_t* s){
s=(student_t*)malloc(sizeof(student_t));
s->name=(char*)malloc(sizeof(char)*STRLIM);
fflush(stdin);
fgets(s->name,STRLIM,stdin);
return s;
}
Gdb ouput shown in the attached image here.
Please check out my repo.
I am guessing something about my build and datatypes is off .Thanks in advance.

Learning to process files. Trying to think of a method for maintaining file pointer position

I am working on a program to store data from a text file within a structure. The goal is to perform the file processing completely within the function outside of the main. The function opens and closes the file, and when it is called by the main function it is to populate the particular structure array element is supposed to be performed upon. The test file I am using is just a text file containing 3 lines:
Gates M 60
Jobs M 55
Jane F 45
These should be populated into an array of structures when called by the function. However, when I call the function it only populates the same first line to all array elements, I believe because the file pointer resets everytime I call the function. How can I remedy this? My code is below!
#include <stdio.h>
struct Individual
{
char LastName[30];
char gender;
unsigned int age;
};
int function(struct Individual *person)
{
FILE *cfPtr;
char holder[100];
cfPtr = fopen("C:\\Users\\Nick\\Desktop\\myfile","r");
fscanf(cfPtr, "%10s %c %3d", &person->LastName, &person->gender, &person->age);
fclose(cfPtr);
}
int main(void)
{
struct Individual person[3];
function(&person[0]);
function(&person[1]);
printf("%s %c %d", person[0].LastName, person[0].gender, person[0].age);
printf("%s %c %d", person[1].LastName, person[1].gender, person[1].age);
return 0;
}
FILE already tracks position for you; you don't need to do it yourself. The problem is that you keep re-opening the file, which resets the location back to the beginning of the file each time.
Open it once, read multiple times, then close it. Make your function take a FILE * parameter.
#include <stdio.h>
struct Individual
{
char LastName[30];
char gender;
unsigned int age;
};
int function(FILE *cfPtr, struct Individual *person)
{
fscanf(cfPtr, "%10s %c %3d", &person->LastName, &person->gender, &person->age);
// TODO: Check for failure
// TODO: Return appropriate value
}
int main(void)
{
struct Individual person[3];
FILE *cfPtr;
cfPtr = fopen("C:\\Users\\Nick\\Desktop\\myfile","r");
// TODO: Check for failure
function(cfPtr, &person[0]);
function(cfPtr, &person[1]);
fclose(cfPtr);
printf("%s %c %d", person[0].LastName, person[0].gender, person[0].age);
printf("%s %c %d", person[1].LastName, person[1].gender, person[1].age);
return 0;
}

C programming - why garbage data inside my struct?

I have the following program in C:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef struct str{
char * s;
int len;
}string;
typedef struct stud{
unsigned int id;
string name;
char gender;
}student;
student* addstud(const int id, const char name[64], const char gender);
student* addstud(void){
char buf[64];
struct stud *sb;
sb = (struct stud*)malloc(sizeof(struct stud));
printf("Enter student ID:\n");
scanf("%d",&sb->id);
printf("Enter student name:\n");
scanf("%s", buf);
sb->name.s = buf;
sb->name.len = (int)strlen(buf);
printf("Enter student gender:\n");
scanf(" %c", &sb->gender);
printf("Student ID: %d, name: %s, gender: %c\n", sb->id, sb->name.s, sb->gender);
return sb;
}
int main(){
student *mystudent;
mystudent=addstud();
printf("Student ID: %d, name: %s, gender: %c\n", mystudent->id, mystudent->name.s, mystudent->gender);
getchar();
return 0;
}
In the addstud() function, everthing is fine but in main() when I try to print out the student name from mystudent->name.s it just garbage data. I don't understand why this could happened as it was clearly fine in addstud() function and both pointers point to the same memory address :( Could anyone please shred some light what I did wrong here, please? Thank you!
you can duplicate the buf.
sb->name.s = strdup(buf);
char buf[64];
Here buf is local to function addstud() so once you exit the function this array is out of scope and accessing it will lead to undefined behavior.
sb->name.s = buf;
In this, buf is a local variable to the function addstud(). So, when the function exits, accessing the variable is UB.
You have 2 options,
1)Either allot memory for buf using malloc()
2) Use strcpy() to copy the contents of the variable buf to sb->name.s

Resources