Having problems replacing data in array - c

For a project I have to do, I have to list a set of classes, have the user select which class to use, and print out a weekly schedule for them for the semester. (Same program as the first question I asked.) However, I seem to run into a problem when I try to print out a weekly schedule. (The program is pretty lengthy, at least with the experience I have in C.)
struct course
{
int index;
char name[7];
char day[4];
int hours,houre,mins,mine;
char ap[3];
int credit;
};
struct course whcl[]={ {0,"MATH1","MWF",7,8,30,50,"AM",5},
{1,"MATH2","MWF",9,10,00,20,"AM",5},
{2,"CHEM1","MW ",2,6,30,50,"PM",5},
{3,"PHYS4","TTH",4,6,00,45,"PM",4},
{4,"ENGR1","M ",9,10,30,20,"AM",1},
{5,"ENGR2","TTH",10,12,00,15,"PM",3},
{6,"ENGR3","MW ",11,12,00,15,"PM",3}};
int choice[15],i,j,k,num,z,s;
void printout(int z); //(To be put in when I fix the function)
int main(void)
{
char l[8][3]={{"st"},{"nd"},{"rd"},{"th"},{"th"},{"th"},{"th"},{"th"}};
printf(" Fall Schedule\n");
printf("Index Course Day Time Credit\n");
printf("-------------------------------------------\n");
for(i=0;i<7;i++)
{
printf(" %i %s %s %i%i:%i%i-%i%i:%i%i%s %i\n",
whcl[i].index,whcl[i].name,whcl[i].day,
whcl[i].hours/10,whcl[i].hours%10,
whcl[i].mins/10,whcl[i].mins%10,
whcl[i].houre/10,whcl[i].houre%10,
whcl[i].mine/10,whcl[i].mine%10,
whcl[i].ap,whcl[i].credit);
}
printf("How many classes would you like to take?: ");
scanf("%i",&num);
for(i=0;i<num;i++)
{
printf("Select the %i%s class using the index: ",i+1,l[i]);
scanf("%i",&choice[i]);
}
printf("The classes you have selected are:\n");
printf("Index Course Day Time Credit\n");
printf("-------------------------------------------\n");
for(i=0;i<num;i++)
{
s=choice[i];
printf(" %i %s %s %i%i:%i%i-%i%i:%i%i%s %i\n",
whcl[s].index,whcl[s].name,whcl[s].day,
whcl[s].hours/10,whcl[s].hours%10,
whcl[s].mins/10,whcl[s].mins%10,
whcl[s].houre/10,whcl[s].houre%10,
whcl[s].mine/10,whcl[s].mine%10,
whcl[s].ap,whcl[s].credit);
}
printf("Your weekly schedule for Fall is:\n");
printf(" Time Monday Tuesday Wednesday Thursday Friday\n");
printout(z);
return 0;
}
void printout(int z)
{
int start,starti,end,endi,num;
int slot[25][6];
for(i=0;i<24;i++)
for(j=0;j<5;j++)
slot[i][j]=99;
for(i=0;i<num;i++)
{
if ((whcl[choice[i]].day)=="MWF")//I think the problem is here.
{
start=whcl[choice[i]].hours*60+whcl[choice[i]].mins;
end=whcl[choice[i]].houre*60+whcl[choice[i]].mine;
starti=(start-450)/30;
endi=(end-450)/30;
for(j=starti;j<=endi;j++)
slot[j][1]=slot[j][3]=slot[j][6]=whcl[choice[i]].index;
}
}
for(i=0;i<24;i++)
{
printf("%i%i:%i%i-%i%i:%i%i ",
(450+(i-1)*30)/60/10,(450+(i-1)*30)/60%10,
(450+(i-1)*30)%60/10,(450+(i-1)*30)%60%10,
(450+(i-1)*30+30)/60/10,(450+(i-1)*30+30)/60%10,
(450+(i-1)*30+30)%60/10,(450+(i-1)*30+30)%60%10);
for(j=0;j<4;j++)
{
if (slot[i][j]!=99) //Use Note here
printf(" %s ",whcl[choice[i]].name);
else
printf("");
}
printf("\n");
}
return;
}
When I print out the schedule, the only thing that comes up is the time. Everything else is blank. I think it's due to my trying to replace the slot array with something other than 99. If you plan on running this program, please use 2 the amount of classes you want to take, and use 0 and 1 for the index on the class choice. (I don't have any if statements and whatnot to take into account the other classes the user might have chosen.) Here's a photo of what I'm trying to do for my program. http://postimg.org/image/3tlgtwu9h/ I used paint to put in the boxes on the schedule to visually see the different arrays as I was coding.
Note: If you change the if statement to [i][j]==99 You can see the "Class" being printed on the table, however it fills up the entire array slot, which confirms my thought that I messed up on trying to replace data in the array. Also, I filled it up with 99 to make 99 associated with blank spaces.

if ((whcl[choice[i]].day)=="MWF") //I think the problem is here.
Correct, you need to use strcmp to compare strings, not ==
Try:
if (strcmp(whcl[choice[i]].day,"MWF") == 0)
Equality as == will check if pointers are the same so you could have:
char * a = "MTW"; char *b = a and then a == b would be true

Related

Trying to create a loop that has an array continuously add data within it that the user creates

I just want to quickly note that im a third semester CS student so im fairly new to C and I just really want help on a project im creating for myself.
Okay so basically im trying to have it so that I create a question that the code asks the user such as "Type in your name, age, and house" (im trying to create this harry potter quiz for my gf). So I want to store the user information within an array inside of this structure I created. I want it so that the user puts down their information and it stores it in the structure and then later the user can add another person to compare their results to and itll store this users data as well and whenever you want to print it all itll print it. Im hoping this makes sense so please feel free to ask questions but ill
#include<stdio.h>
#include <stdlib.h>
#include "sortinghatquiz.h"
#define maxNum 100
int main_sorting_quiz()
{
sorting_hat_menu();
sorting_hat_switch();
}
int sorting_hat_menu()
{
char array[]={"."};
for (int i = 0; i < 50; i++)
{
printf("%c\n", array[0]);
}
printf("\n\n\t\t\tWelcome to the Hogwarts Sorting Hat Quiz!!!\n");
printf("\t\t\t________________________________________\n");
printf("\t\t\t1 - Start the quiz!\n\t\t\t2 - Find Existing Quiz!\n\t\t\t3 - Compare results with another user!\n\t\t\t4 - Return to main menu!\n\n");
}
int sorting_hat_switch()
{
int choice_quiz,x;
printf("\n\t\t\tChoose your option: ");
scanf("%d", &choice_quiz);
switch (choice_quiz)
{
case 1:
start_quiz(x);
break;
case 2:
find_quiz();
break;
case 3:
compare_results();
break;
default:
break;
}
}
int start_quiz(quizinfo *i)
{
quizinfo A[maxNum] = {};
for (i = 0; i < 4; i++)
{
start_quiz_menu(i);
return i;
}
printf("\nHeres the first persons data %s, %s, %s\n", A[0].name, A[0].age, A[0].house);
printf("\nHeres the second persons data %s, %s, %s\n", A[1].name, A[1].age, A[1].house);
printf("\nHeres the third persons data %s, %s, %s\n", A[2].name, A[2].age, A[2].house);
printf("\nHeres the fourth persons data %s, %s, %s\n", A[3].name, A[3].age, A[3].house);
//Type in your name
//Type in your age
//Type in your desired house (this wont influence your decision)
//All of this data needs to be stored within structure
}
int start_quiz_menu(quizinfo *x)
{
int i;
quizinfo A[maxNum] = {};
printf("\t\t\tType your name in: ");
scanf("%s", A[i].name);
printf("\n\t\t\tType in your age: ");
scanf("%s", A[i].age);
printf("\n\t\t\tType in your desired house to see if you think you know yourself: ");
scanf("%s", A[i].house);
printf("\n\n\t\t\tHello %s, at the age of %s you have begun your quest to see which hogwarts house you are placed in.\n\t\t\tLets see if %s really is your true house.....\n", A[i].name, A[i].age, A[i].house);
}
int find_quiz()
{
printf("Find Quiz Test 1");
}
int compare_results()
{
printf("Compare results Test 1");
}
Im experimenting with libraries so its all connected and compiled into one main.c file so heres the .h file for this piece of code
#ifndef _SORTINGHATQUIZ_H_
#define _SORTINGHATQUIZ_H_
typedef struct
{
char name[100];
int age[10];
char house[100]
}quizinfo;
int main_sorting_quiz();
int sorting_hat_menu();
int start_quiz(quizinfo *i);
int start_quiz_menu(quizinfo *x);
int find_quiz();
int compare_results();
#endif
Also like I said, im fairly new to this so If theres anything I can optimize to make more efficient then I would love to hear some advice. Thanks!

how do I print the stuct members using an array pointers?

The code I have wrote so far is the following without the libraries. Basically I used the stdio.h and the stdlib.h.
typedef struct ID{
char firstName[21];
char lastName[21];
char phoneNumber[11];
}ID;
ID PrintList(ID *ptr,int i){
int l=1;
printf(" # First Name Last Name Phone Number\n");
while(l<i+1)
{
printf(" %d. %s",l,&ptr[l]);
l++;
}
}
ID addNew(ID *ptr,int i){
char fname[21],lname[21],phone[11];
if(i<3)
{
ID user;
ptr[i] = user;
printf("enter the first name: ");
scanf("%s",&fname);
*ptr->firstName= fname;
printf("enter the last name: ");
scanf("%s",&lname);
*ptr->lastName = lname;
printf("enter the phone number: ");
scanf("%s",&phone);
*ptr->phoneNumber = phone;
}
else
{
printf("sorry but you have reach max capacity\n");
}
}
int main(int argc, char *argv[]) {
int answere,i=0;
printf("******* WELCOME TO PHONEBOOK **********\n\n\n");
printf("***************************************\n");
printf("* MENU *\n");
printf("* *\n");
printf("* 1.Add New 2.Print list 3.Exit *\n\n");
printf("***************************************\n\n");
ID* ptr=(int*)malloc(21*sizeof(ID));
do
{
printf("Please select (1, 2 or 3): ");
scanf("%d",&answere);
if(answere!=1 && answere!=2 && answere!=3)
{
printf("...Error... \ngive me a correct answere\n");
}
if(answere == 1)
{
i++;
addNew(ptr,i);
}
else if(answere==2)
{
PrintList(ptr,i);
}
}while(answere!=3);
return 0;
}
So as I said my problem is that I am not able to print the members of the struct as I need to print them using the array of pointers though. I think that I just haven't written something right like it is just a little logic mistake in printf.
The only obstacle that I have is that the array of pointers is needed to be made in main.
You seem completely lost...
Some Basics
You are passing pointer/reference to first item of an array (address of the first item)
to get value at that address (dereference it) you can do two things:
*ptr //but I don't recommend using it with structures
ptr[0]
since you are using structures that are generally big you are expected to work with pointers and for that reason so called "arrow" operator exists which can be used to access members of structure pointer
ptr->firstName
So your function would look like this:
void PrintList(ID *ptr, int l)
{
int i;
printf(" # First Name Last Name Phone Number\n");
for(i = 0; i < l; i++)
{
printf("%2d. %s %s %s\n",
i, ptr[i].firstName, ptr[i].firstName, ptr[i].phoneNumber);
}
}
Also I recommend using '\t' instead of spaces to align the columns.

Defining functions that return a char used later in the main program

I am having a lot of trouble wrapping my head around calling functions and using them in the main program again later. I have not found an answer in depth to explain why this doesn't run. I understand that parameters belong inside of the called function parentheses, but I want the user input to begin in the called program. Is this even possible? Theoretically, the function would ask the user for a year, check that it is within certain parameters, then return it to the main function where I would like to eventually be able to store it in an array. For now, can someone please show me how I would make that work in this elementary program? Thank you in advance!
#include <stdio.h>
char year_info();
int main(void)
{
int menu_selection;
char year;
printf("Please choose from the following menu: \n1. Insert a new movie\n2. Show movie\n3. List all\n4. Exit\n");
scanf("%i", &menu_selection);
switch (menu_selection)
{
case 1: year = year_info();
printf("%c", year);
break;
}
}
char year_info()
{
int year_input;
printf("\nYear: ");
scanf("%i", &year_input);
if (year_input > 2016 || year_input < 1920)
{
printf("Sorry, I do not recognize this command. Please try again.\n");
}
else
{
int year = year_input;
return year;
}
}
It doesn't run because you're passing scanf the variable, but you should pass the address of the variable, i.e. use:
scanf("%i", &something);
instead of scanf("%i", something);
Also, as others pointed out, you're mixing char and int too liberally, so it won't work as expected.
year and year_imput can't be chars because they won't hold values large enough, you'll need at least a short.
You had 2 errors.
scanf("%i", &menu_selection);
scanf("%i", &year_imput);
You need to use the & to pass the address of the variables to scanf().
Edit: However, I would have used an integer for that, because a scanf("%c", &something) will only recognize the first char you enter, and not the whole string, even if that happened you can't do if (year_imput > 2016 || year_imput < 1920) between strings, you can do that with chars, but again, they can only store one character, so I would have done your program like this.
#include <stdio.h>
int year_info();
int main() {
int menu_selection;
int year;
printf("Please choose from the following menu: \n1. Insert a new movie\n2. Show movie\n3. List all\n4. Exit\n");
scanf("%i", &menu_selection);
switch (menu_selection) {
case 1:
year = year_info();
printf("%i", year);
break;
default:
break;
}
return 0;
}
int year_info() {
int year_imput;
printf("\nYear: ");
scanf("%i", &year_imput);
if (year_imput > 2016 || year_imput < 1920) {
printf("Sorry, I do not recognize this command. Please try again.\n");
return 0;
}
else
return year_imput;
}

How to approach and optimize code in C

I am new to C and very much interested in knowing how to approach any problem which has more than 3 or 4 functions, I always look at the output required and manipulate my code calling functions inside other functions and getting the required output.
Below is my logic for finding a students record through his Id first & then Username.
This code according to my professor has an excessive logic and is lacking in many ways, if someone could assist me in how should I approach any problem in C or in any other language it would be of great help for me as a beginner and yes I do write pseudo code first.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int id; //Assuming student id to be unique
int age;
char *userName; //Assuming student userName to be unique
char *dept;
}student; // Alias "student" created for struct
student* createstruct(); // All function prototype declared
student* createArray();
void addstruct(student* s2);
void searchChar(student* s2,int num);
void searchInt(student* s2,int num);
student* createstruct() // function createStruct() to malloc data of struct student.
{
student *s;
s = (student*)malloc(sizeof(student));
s->userName = (char*)malloc(sizeof(char)*32);
s->dept = (char*)malloc(sizeof(char)*32);
printf("please enter id ");
scanf("%d",&s->id);
printf("please enter age ");
scanf("%d",&s->age);
printf("please enter userName ");
scanf("%31s",s->userName);
printf("please enter department ");
scanf("%31s",s->dept);
printf("\n");
return s;
}
student* createArray()
{
student *arr; //declaration of arr poiter, type struct student
arr = (student*)malloc(sizeof(student)*10); // memory allocated for a size of 10
return arr;
}
void addstruct(student *s2) // function for adding data to the structures in array
{
int i,num;
student* s1;
printf("please enter the number of records to add:");
scanf("%d",&num);
printf("\n");
if(num>0 && num<11)
{
for(i=0;i<num;i++) // if user want to enter 5 records loop will only run 5 times
{
s1 = createstruct();
s2[i].id = s1->id; // traversing each element of array and filling in struct data
s2[i].age = s1->age;
s2[i].userName = s1->userName;
s2[i].dept= s1->dept;
}
}
else if(num>10) // if user enters more than 10
{
for(i=0;i<10;i++) // loop will still run only 10 times
{
s1 = createstruct();
s2[i].id = s1->id;
s2[i].age = s1->age;
s2[i].userName = s1->userName;
s2[i].dept = s1->dept;
}
printf("Array is full"); // Array is full after taking 10 records
printf("\n");
}
searchInt(s2,num); // Calling searchInt() function to search for an integer in records
searchChar(s2,num); // Calling searchChar() function to search for a string in records
free(s1);
free(s2);
}
void searchChar(student* s2,int num) // function for searching a string in records of structure
{
char *c;
int i;
c = (char*)malloc(sizeof(char)*32);
printf("please enter userName to search ");
scanf("%31s",c);
printf("\n");
for (i=0;i<num;i++) //num is the number of struct records entered by user
{
if ((strcmp(s2[i].userName,c)==0)) //using strcmp for comparing strings
{
printf("struct variables are %d, %d, %s, %s\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
break;
}
else if(i == num-1)
{
printf("nothing in userName matches: <%s>\n",c);
break;
}
}
}
void searchInt(student* s2,int num) //searchs for an integer and prints the entire structure
{
int i,z;
printf("please enter id to search ");
scanf("%d",&z);
printf("\n");
for (i=0;i<num;i++)
{
if (s2[i].id == z)
{
printf("struct variables are %d, %d, %s, %s\n\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
break;
}
else if(i == num-1)
{
printf("nothing in id matches: <%d>\n\n",z);
break;
}
}
}
int main(void)
{
student *s2;
s2 = createArray();
addstruct(s2);
return 0;
}
I'm not going to go into optimizing, because if you wanted better theoretical performance you would probably go with different data structures, such as ordered arrays/lists, trees, hash tables or some kind of indexing... None of that is relevant in this case, because you have a simple program dealing with a small amount of data.
But I am going to tell you about the "excessive logic" your professor mentioned, taking your searchInt function as an example:
for (i=0;i<num;i++)
{
if (s2[i].id == z)
{
printf("struct variables are %d, %d, %s, %s\n\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
break;
}
else if(i == num-1)
{
printf("nothing in id matches: <%d>\n\n",z);
break;
}
}
The thing here is that every time around the loop you're testing to see if you're at the last element in the loop. But the loop already does that. So you're doing it twice, and to make it worse, you're doing a subtraction (which may or may not be optimized into a register by the compiler).
What you would normally do is something like this:
int i;
student *s = NULL;
for( i = 0; i < num; i++ )
{
if( s2[i].id == z ) {
s = &s2[i];
break;
}
}
if( s != NULL ) {
printf( "struct variables are %d, %d, %s, %s\n\n",
s->id, s->age, s->userName, s->dept );
} else {
printf("nothing in id matches: <%d>\n\n",z);
}
See that you only need to have some way of knowing that the loop found something. You wait for the loop to finish before you test whether it found something.
In this case I used a pointer to indicate success, because I could then use the pointer to access the relevant record without having to index back into the array and clutter the code. You won't always use pointers.
Sometimes you set a flag, sometimes you store the array index, sometimes you just return from the function (and if the loop falls through you know it didn't find anything).
Programming is about making sensible choices for the problem you are solving. Only optimize when you need to, don't over-complicate a problem, and always try to write code that is easy to read/understand.

C - array count, strtok, etc

i have a little problem on my code...
HI open a txt that have this:
LEI;7671;Maria Albertina da silva;xxxx#gmail.com;
9;8;12;9;12;11;6;15;7;11;
LTCGM;6567;Artur Pereira Ribeiro;fdsdfsd#gmail.com;
6;13;14;12;11;16;14;
LEI;7701;Ana Maria Carvalho;asasssas#gmail.com;
8;13;11;7;14;12;11;16;14;
LEI, LTCGM are the college;
7671, 6567, 7701 is student number;
Maria, Artur e Ana are the students name;
xxxx#gmail.com, ...#gmail are emails from students;
the first number of every line is the total of classes that students have;
after that is students school notes;
example:
College: LEI
Number: 7671
Name: Maria Albertina da Silva
email: xxxx#gmail.com
total of classes: 9
Classe Notes: 8 12 9 12 11 6 15 7 11.
My code:
typedef struct aluno {
char sigla[5];//college
char numero[80];//number
char nome[80];//student name
char email[20];//email
int total_notas;// total of classes
char tot_not[40]; // total classes
char notas[20];// classe notes
int nota; //class notes
char situacao[80]; //situation (aproved or disaproved)
} ALUNO;
void ordena(ALUNO*alunos, int tam)//bubble sort
{
int i=0;
int j=0;
char temp[100];
for (i=0;i<tam;i++)
for (j=0;j<tam-1;j++)
if (strcmp( alunos[i].sigla[j], alunos[i].sigla[j+1])>0)
{
strcpy(temp, alunos[i].sigla[j]);
strcpy(alunos[i].sigla[j],alunos[i].sigla[j+1]);
strcpy(alunos[i].sigla[j+1], temp);
}
}
void xml(ALUNO*alunos, int tam)
{
FILE *fp;
char linha[60];//line
int soma, max, min, count;//biggest note and lowest note and students per course count
float media; //media of notes
fp=fopen("example.txt","r");
if (fp==NULL)
{
exit(1);
}
else
{
while (!(feof(fp)))
{
soma=0;
media=0;
max=0;
min=0;
count=0;
fgets(linha,60,fp);
if (linha[0]=='L')
{
if (ap_dados=strtok(linha,";"))
{
strcpy(alunos[i].sigla,ap_dados);//copy to struct
// i need to call bubble sort here, but i don't know how
printf("College: %s\n",alunos[i].sigla);
if (ap_dados=strtok(NULL,";"))
{
strcpy(alunos[i].numero,ap_dados);//copy to struct
printf("number: %s\n",alunos[i].numero);
if (ap_dados=strtok(NULL,";"))
{
strcpy(alunos[i].nome, ap_dados);//copy to struct
printf("name: %s\n",alunos[i].nome);
if (ap_dados=strtok(NULL,";"))
{
strcpy(alunos[i].email, ap_dados);//copy to struct
printf("email: %s\n",alunos[i].email);
}
}
}
}
i++;
}
if (isdigit(linha[0]))
{
if (info_notas=strtok(linha,";"))
{
strcpy(alunos[i].tot_not,info_notas);
alunos[i].total_notas=atoi(alunos[i].tot_not);//total classes
for (z=0;z<=alunos[i].total_notas;z++)
{
if (info_notas=strtok(NULL,";"))
{
strcpy(alunos[i].notas,info_notas);
alunos[i].nota=atoi(alunos[i].notas); // student class notes
}
soma=soma + alunos[i].nota;
media=soma/alunos[i].total_notas;//doesn't work
if (alunos[i].nota>max)
{
max=alunos[i].nota;;//doesn't work
}
else
{
if (min<alunos[i].nota)
{
min=alunos[i].nota;;//doesn't work
}
}
//now i need to count the numbers of students in the same college, but doesn't work
/*If(strcmp(alunos[i].sigla, alunos[i+1].sigla)=0){
count ++;
printf("%d\n", count); here for LEI should appear 2 students and for LTCGM appear 1, don't work
}*/
//Now i need to see if student is aproved or disaproved
// Student is disaproved if he gets 3 notes under 10, how can i do that?
}
printf("media %d\n",media); //media
printf("Nota maxima %d\n",max);// biggest note
printf("Nota minima %d\n",min); //lowest note
}
i++;
}
}
}
fclose(fp);
}
int main(int argc, char *argv[])
{
ALUNO alunos;
FILE *fp;
int tam==3;
fp=fopen("example.txt","r");
alunos = (ALUNO*) calloc (tam, sizeof(ALUNO));
xml(alunos,nomeFicheiro, tam);
system("PAUSE");
return 0;
}
If you need to call bubble sort, why won't
ordena(alunos, tam);
work? (Hint: where is the contiguous memory where you store an entire sequence of records?)
(Hint #2: does it make sense to try to sort before you have read in all the records?)
By the way, I urge you most strongly to indent your code to make it readable. Not only will you get a better grade, but it will make it easier to help you. I'm pretty confident that the call I suggest won't work, but because almost all your code is in the left margin, I'm not sure.
You also might want to ask what are the different tasks here (read one record, read all records, sort all records, print records from a single colleage) and see if you can't find a way to organize your code such that you are using one of the available language constructs to separate one task from another. (I'm being deliberately cryptic because I don't know what you've yet to study. You should definitely ask your instructor or teaching assistant about this question.)
I think you also might wish to consider whether your bubble sort is doing the right thing. I suggest you "play computer" by executing your code by hand on an example where tam == 3.

Resources