C store values in an array - c

My program reads the following data: Date, Distance and Time.
So for example an input would look like:
Date: 10.10.2013
Distance (m): 500
Time (HH:MM:SS): 01:20:05
I want to store all this information in an array. The problem is that I want the user to input date, distance and time several times and the program has to save all the data in an array.
I can't store it like this, because then how would I know which index is the date index? And how should I store the time? I can't store it with :.
arr[0] = 10.10.2013
arr[1] = 500
arr[2] = 012005
arr[3] = 22.10.2013
arr[4] = 200
arr[5] = 000510

You can make a struct:
struct Data{
Date date;
Distance distance;
Time time;
}
Then declare an array of Data and use it like that:
Data arr[5];
arr[0].date = //some date;
arr[0].distane =//some distance
arr[0].time=//some time

Because the type of data you will need to store, it needs type char, so it can be stored in strings. (i.e. "10.10.2013")
First, Define a struct PARAM:
typedef struct {
char date[20];
char distance[20];
char time[20];
} PARAM;
use PARAM to create an array of your struct:
PARAM param[20];
Now, you can use it like this for example:
int main(void)
{
strcpy(param[0].date, "10.10.2013");
strcpy(param[0].time, "05:02:10");
strcpy(param[0].distance, "500");
//and so on for all the struct array elements, 0 through 20
return 0;
}
Or, better yet, using printf() and scanf() statements as necessary, you can prompt the user for input in a loop, and store in your struct array:
int main(void)
{
int i;
for(i=0;i<20;i++)
{
printf("enter date %d:", i+1);
scanf("%s", param[i].date);
printf("enter distance %d:", i+1);
scanf("%s", param[i].distance);
printf("enter time %d:", i+1);
scanf("%s", param[i].time);
}
return 0;
}
EDIT Regarding question in comment Therefore I guess its best to store them in date.day, date.month and date.year. Right? That approach would work, and I include it below, but it is a little more tedious to enter data that way. I included a second example below that might improve both, entering data, and storing data.
So, Per your comment, two ways jump to mind:
ONE, create struct members that contain the discrete members of time and date as integers: i.e.
typedef struct {
int day;
int month;
int year;
int hour;
int minute;
int second;
}TIMEDATE;
Use this struct as a member of the PARAM struct;
typedef struct {
int distance;
TIMEDATE timedate;
}PARAM;
PARAM param[20];
Now, just modify and expand the example of the last main() function to include scanning in values for the new struct members. This will be more tedious for the person using your program, but will allow you to keep all the input values as numbers as you have indicated.
//Note the changes in scanf format specifiers for int, "%d":
// in all the statements
int main(void)
{
int i;
for(i=0;i<20;i++)
{
printf("enter date %d:", i+1);
scanf("%d", &param[i].timedate.day);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.month);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.year);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.hour);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.minute);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.second);
printf("enter time %d:", i+1);
scanf("%d", &param[i].distance);
}
return 0;
}
Two, modify the first approach to include using strings AND integers, all in the same struct. This will make it easier for the user user to enter time and date information, and possible for you to manipulate the data easier. And a bonus, it will demonstrate how to parse the user input string data into integer data.
typedef struct {
char date[20];//keep as char
char time[20];//keep as char
int distance; //changed to int
TIMEDATE timedate;//container for in data
} PARAM;
//use PARAM to create an array of your struct:
PARAM param[20], *pParam; //create a pointer to pass
int GetIntData(PARAM *p, int index);//prototype for new function
//Note the changes in scanf format specifiers for int, "%d":
// in all the statements
int main(void)
{
int i, loops;
pParam = &param[0]; //initialize pointer to struct
printf("How many sets of data would you like to enter? :");
scanf("%d", &loops);
for(i=0;i<loops;i++)
{
printf("enter date (eg:MM.DD.YYYY): %d:", i+1);
scanf("%s", pParam[i].date);
printf("enter time (eg HH:MM:SS): %d:", i+1);
scanf("%s", pParam[i].time);
printf("enter distance %d:", i+1);
scanf("%d", &pParam[i].distance);
GetIntData(pParam, i);
}
return 0;
}
//reads string members into integer members
int GetIntData(PARAM *p, int index)
{
char *buf=0;
if(strstr(p[index].date, ".")==NULL) return -1;
p[index].timedate.month = atoi(strtok(p[index].date, "."));
p[index].timedate.day = atoi(strtok(NULL, "."));
p[index].timedate.year = atoi(strtok(NULL, "."));
if(strstr(p[index].time, ":")==NULL) return -1;
buf=0;
p[index].timedate.hour = atoi(strtok(p[index].time, ":"));
p[index].timedate.minute = atoi(strtok(NULL, ":"));
p[index].timedate.second = atoi(strtok(NULL, ":"));
return 0;
}

Related

What this error mean : expression must have pointer to object type but it has type struct add_stock in c

#include <stdio.h>
int i, n;
struct add_stock
{
char fullname[30];
int stocks;
char com_name[30];
int shares;
float price;
float total;
int totalmoney;
} add;
int main()
{
printf("Enter full name : ");
scanf(" %[^\n]s", add.fullname);
printf("Enter the no. of stocks you want to purchased : ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the name of the company : ");
scanf(" %[^\n]s", add[i].com_name);
printf("Enter the no. of shares you want to purchased : ");
scanf("%d", &add[i].shares);
printf("Enter the price of each share : ");
scanf("%f", &add[i].price);
add.total = add.shares * add.price;
printf("Toatl money invested in this stock : ");
scanf("%f", &add[i].total);
}
printf("Total money invested : ");
scanf("%d", add.totalmoney);
return 0;
}
In question it's add_stock , not add stock , i write like this becoz it's not accepting question.
So, i get error for "add" saying subscripted value is neither array nor pointer nor vector.
To declare an array of strucuture, you need to define the variable as below,
struct add_stock
{
char fullname[30];
int stocks;
char com_name[30];
int shares;
float price;
float total;
int totalmoney;
} add[20];
this makes the add as an array of add_stock elements.
then you can access it as, add[0].total, add[1].price and so on.
If you want to declare an array that need to be having dynamic number of elements, you can do so as below.
struct add_stock* arStock;
//allocate memory to hold 10 elements
arStock = (add_stock*)malloc( 10 * sizeof(struct add_stock));
arStock[0]->total=10; //access it with ->, instead of .

C structure type variable declaration

I have written a code for a ticket reservation halfway and I'm doubtful about the way i have used structures and arrays in my code. This code is not formatted properly because I am trying to see if this method of declaring "Bill" type variable will work or is this wrong?
the code gets compiled and runs successfully but I am doubtful whether my method is correct. Can anyone help? I just want to know whether the way I have declared structure type variables and used it is correct?Especially the last printf statement where I calculate the Amount.
#include<stdio.h>
#include<string.h>
#define SIZE 3
typedef struct
{
int billno;
char name[20];
char cat[20];
int type;
int range[3];
int tickets;
int class[3];
float price;
}Bill;
int main()
{
Bill array[3];
Bill d;
int input;
array[0].billno=6434;
strcpy(array[0].name,"Nimal");
strcpy(array[0].cat,"General");
array[0].type=1;
array[0].range[0]= 250;
array[0].range[1]= 0;
array[0].range[2]= 0;
array[0].price = 200;
array[1].billno=6065;
strcpy(array[1].name,"Kamal");
strcpy(array[1].cat,"Industrial");
array[1].type=2;
array[1].range[0]=622;
array[1].range[1]=1999;
array[1].range[2]=102;
array[1].price =125.60;
array[2].billno=7067;
strcpy(array[2].name,"Gayani");
strcpy(array[2].cat,"General");
array[2].type=2;
array[2].range[0]=220;
array[2].range[1]=350;
array[2].range[2]=10;
array[2].price = 86.90;
printf("****Main Menu****");
printf("1.Reserve a ticket:");
scanf("%d",&input);
if(input == 1)
{
printf("Enter your name: ");
scanf("%s", d.name);
printf("Enter the number of tickets you want");
scanf("%d",&d.tickets);
printf("Enter the number of tickets from first class");
scanf("%d",&d.class[0]);
printf("Enter the number of tcikets from second class");
scanf("%d",&d.class[1]);
printf("Enter the number of tickets from third class");
scanf("%d",&d.class[2]);
}
printf("\nReserve a ticket");
printf("\nName : %s",d.name);
printf("\nTickets from first class : %d",d.class[0]);
printf("Tickets from second class : %d\n",d.class[1]);
printf("Tickets from third class : %d\n",d.class[2]);
printf("\nConfirm the order? press Y if yes : ");
printf("Amount = %.2f ",d.class[0]*array[0].price+d.class[1]*array[1].price+d.class[2]*array[2].price);
return 0;
}

confusion comparing structures

the question is to calculate the average of each student separately and then show the id and the average of rank one student. how to compare members of structure
#include<stdio.h>
typedef struct student
{
int id;
float math,physics;
float av;
}std;
int main()
{
int i;
std p[5];
for(i=0;i<5;i++)
{
printf("enter student(%d) id: ",i+1);
scanf("%d",&p[i].id);
printf("grade of math over 100: ");
scanf("%f",&p[i].math);
printf("grade of physics over 100: ");
scanf("%f",&p[i].physics);
printf("average=%.3f\n\n",(p[i].math+p[i].physics)/2);
}
}
To compare on element with another you would take either
p[index]->av {comparaision} p[index]->av
Example p[0]->av > p[1]->av
Don't forget printf("average=%.3f\n\n",(p[i].math+p[i].physics)/2); will print you the result of av but will not save it in p. Save it in p[index].av to be able to do comparaisons.
Then afterward just do a loop where you compare each of them and save their id in an array. The array should be based on a decreasing average with the matching id. Then just print the array and you will be good to go.
#include<stdio.h>
typedef struct studentd
{ int id;
float math,physics;
float av;
} std;
int main()
{
int i,a;
std p[5];
for(i=0; i<5; i++)
{
printf("student(%d) id: ",i+1);
scanf("%d",&p[i].id);
printf("grade of math over 100: ");
scanf("%f",&p[i].math);
printf("grade of physics over 100: ");
scanf("%f",&p[i].physics);
printf("average=%.3f\n\n",p[i].av=(p[i].math+p[i].physics)/2);
}
int max=p[0].av;
for(i=0; i<5; i++)
{
if(p[i].av<=p[i+1].av)
{
max=p[i].av;
}
}
printf("the highest average is for student: %d ",p[i].id);
return 0;
}
/*END*/
/now this is the updated code my problem is how to link the id of student to the max to show the id of student whi got the highest mark/
Well one of two things,
Either add an integer to track the index of the structure containing the max,
Or instead of
max =p[i].avg
Use max = p[i]
Of course let max be a struct not float or int

(C) Print an array of structs from a function that calls other function

I cooked a code for a program that asks the user to fill in information about a person (ReadDate/ReadPerson), then it asks for the range of people the user wants to print, and the function prints these people. (PrintRange)
I don't understand why the program is not working; it's stuck on the point when it should print the person... it's means there is probably a problem in either PrintPerson or PrintDate, or in the way I am calling these functions.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int day, month, year;
} Date;
typedef struct{
char *first_name, *last_name;
int id;
Date birthday;
} Person;
void ReadDate(Date *a)
{
printf("Enter the day: ");
scanf("%d", &a->day);
printf("Enter the month (1-12): ");
scanf("%d", &a->month);
printf("Enter the year: ");
scanf("%d", &a->year);
}
void ReadPerson(Person *b)
{
char temp_first_name[21];
char temp_last_name[21];
printf("Enter the first name: ");
gets(temp_first_name);
b->first_name = (char*)malloc(strlen(temp_first_name)+1);
strcpy(b->first_name,temp_first_name);
//need to check malloc (later)
printf("Enter the last name: ");
gets(temp_last_name);
b->last_name = (char*)malloc(strlen(temp_last_name)+1);
strcpy(b->last_name, temp_last_name);
//need to check malloc (later)
printf("Enter the id number: ");
scanf("%d",&b->id);
printf("Enter the birthday:\n");
ReadDate(&b->birthday);
}
int ReadAllDate (Person *b)
{
//Person* b;
int count=1;
char choice;
printf("Would you like to enter a person?(y,n)\n");
choice = getchar();
while(choice == 'y')
{
b = (Person*)malloc(1 * sizeof(Person));
getchar();
ReadPerson(b);
printf("Done!\n");
count++;
getchar();
printf("Would you like to add a person?(y,n)\n");
choice = getchar();
}
count--;
printf("The number of entered persons is %d\nBye\n", count);
return count;
}
void PrintPerson(Person b)
{
printf("%s %s %d\n", b.first_name, b.last_name, b.id);
}
void PrintDate(Date a)
{
printf("%d // %d // %d\n",a.day,a.month,a.year);
}
void PrintRange(Person *b,int count,int ind1,int ind2)
{
int i;
if (ind1<0 || ind1>ind2 || ind2>count)
{
printf("error! you slip out from the limits of the array.\n");
}
else
{
for (i=ind1; i<=ind2; i++)
{
PrintPerson(*(b+i));
PrintDate((b+i)->birthday);
}
}
}
int main(int argc, const char * argv[])
{
Person* b;
int count;
int ind1, ind2;
count = ReadAllDate(b);
printf("insert the first index (the smaller): ");
scanf("%d", &ind1);
printf("insert the second index (the bigger): ");
scanf("%d", &ind2);
PrintRange(b, count, ind1, ind2);
}
The problem is that nowhere you are actually creating an array of Person objects. The function ReadAllDate() never changes the value of the variable b in main(). Instead, for every person you read in, it allocates memory for it, and stores the pointer to that Person in the local variable b in ReadAllDate(). Every time it does it, it forgets the previous value of b.
In main(), the value of b is unitinialized all the time. When you are trying to print persons, it will most likely crash or print garbage.
I see other issues with your code:
Don't use gets(), always use fgets(). The former can write past the end of the buffer you are providing.
Don't do malloc(strlen(...))+strcpy(), use strdup().
Start with count = 0, that way you don't need the count-- in ReadAllDate(). As a computer programmer, it's best to count from zero instead of one.
Write b[i] instead of *(b+i), and b[i].birthday instead of (b+i)->birthday.

Array of Structures in C. not linked list

I am having trouble making an array of structures. I want to store data regarding multiple students and take input using the execution of the program. Then output the memory address of persons name with highest marks.
I tried getting to know the answers on similar issues on site, to no help.
The code I have written is
the struct
struct student{
char name;
int marks;
};
and the function is
int num,max = 0,i;
printf("Number of students?\n");
scanf("%d", &num);
struct student* students = (struct student*)malloc (num* (sizeof(struct student)));
for (int x = 0; x < num; x++)
{
printf("Enter Name\n");
scanf("%c" , &students[x].name);
printf("Enter Marks\n");
scanf ("%d" , &students[x].marks);
}
for (i = 1; i < num; i++)
{
if (students[max].marks<students[i].marks)
{
max = i;
}
}
printf("The Memory Add for %c is %p\n", students[max].name , &students[max].name );
It is a part of menu driven program. It goes into a weird loop after line 5 in function code. And i can't create a doubly linked list for the same.
Edit 1
These are the changes i made to struct and func
struct student{
char name[20];
int marks;
};
void memadd(){
int num,max = 0,i, mark;
printf("Number of students?\n");
scanf("%d", &num);
struct student* students = (struct student*)malloc (num* (sizeof(struct student)));
for (int x = 0; x < num; x++)
{
printf("Enter Name\n");
scanf("%s" , &students[x].name);
printf("Enter Marks\n");
scanf ("%d" , &mark);
students[x].marks = mark;
}
for (i = 1; i < num; i++)
{
if (students[max].marks<students[i].marks)
{
max = i;
}
}
printf("The Memory Add for %s is %p\n", students[max].name , &students[max].name );
It is giving an array at input of the name. "format specifies type 'char ' but the argument has
type 'char ()[20]'"
How do I make the format to be char * [20]?
Edit 2
The final working code after correcting the char name to being a character array
And issue with scanning of names.
struct student{
char name[20];
int marks;
};
int num,max = 0,i, mark;
printf("Number of students?\n");
scanf("%d", &num);
struct student* students = (struct student*)malloc (num* (sizeof(struct student)));
for (int x = 0; x < num; x++)
{
printf("Enter Name\n");
scanf("%19s" , students[x].name);
printf("Enter Marks\n");
scanf ("%d" , &mark);
students[x].marks = mark;
}
for (i = 1; i < num; i++)
{
if (students[max].marks<students[i].marks)
{
max = i;
}
}
printf("The Memory Add for %s is %p\n", students[max].name , &students[max].name );
However, what if I wish to print the address in Hex numbers? or the one that am getting is hex already.?
Because I got an output of The Memory Add for XYZ is 0x7fb340c03928
The problem is with the student name being a char and
scanf("%c" , &students[x].name);
What happens is, you read in the number of students with
scanf("%d", &num);
Now you have read num, but there is still a newline in the input buffer.
Then you try to read a character with %c, but this reads the remaining newline.
When you change the student's name to a character array, e.g.
struct student{
char name[20];
int marks;
};
and read the name with
scanf("%19s" , students[x].name);
it will skip the remaining whitespace/newline and read the name as it should.

Resources