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.
Related
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.
I have the following code, in which I must sort book titles by alphabetical order. this is the code I have and am unsure of how to perform the actual sort. any help regarding how to sort more than 2 books would also be appreciated, because the user is prompted to enter up to 30 books.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct Books
{
char title[256];
char author[256];
char genre[256];
int qualityRATE;
int pages;
};
int numberbook = 1;
int casee;
int booksnumber;
int i;
int main()
{
char again;
do
{
printf("how many books will you be entering today?");
scanf("%i", &booksnumber);
printf("Enter the information for your book.\n Name\n Author\n Genre\n quality rating\n\n");
struct Books book1;
struct Books book2;
scanf("%s", book1.title);
scanf("%s", book2.title);
printf("The title of book %i is: %s\n", numberbook, book1.title);
printf("The title of book %i is: %s\n", numberbook, book2.title);
printf("how would you like to sort?\n 1: By title\n 2: by Author\n 3: by pages\n\n");
scanf("%i", &casee);
switch(casee)
{
case 1:
for(i = 1; i < booksnumber, i++;)
{
if(strcmp(book[i].title, book[i+1].title) < 0)
strcpy(book[i+1].title, book[i].title);
else
if(strcmp(book[i+1].title, book[i].title) < 0)
strcpy(book[i].title, book[i+1].title);
}
printf("\n%s\n", book1.title);
break;
case 2:
break;
}
printf("Another book?\n");
numberbook++;
scanf("%s", &again);
}
while(again == 'y');
return 0;
}
I see in your code some problems:
You have to initialize an array of book structures, not book1 and book2, declaring:
struct books book[nnn] /* where nnn is the maximum number of book */
You have to use a counter (should be booksnumber) starting from 0 into the do while loop
You have to use scanf using book[booksnumber] and increment booksnumber for each scanf.
If you want a solid sort engine I suggest you to use the function qsort (qsort is a C library function in stdlib.h)
see: www.cplusplus.com/reference/cstdlib/qsort
A correct way to sort the item should be that in the following code:
struct Books app;
int i,j;
for(i=0;i<booksnumber;i++) {
for(j=i+1;j<booksnumber;j++) {
if (strcmp(book[i].title,book[j].title)<0) {
app=book[i];
book[j]=book[i];
book[i]=app;
}
}
}
I think that the first for loop should be better as below, but I have written this code on the fly and then I have not verified its behavour.
for(i=0;i<booksnumber-1;i++)
I've not verified if the direction of the sort is as you require, if is not you may change the "sign" of the comparation inverting it. IE:
if (strcmp(book[i].title,book[j].title)>0)
For just two books you can use swap. And I think you also need to swap all book properties, not just its title :
void swapBook(struct Books *a, struct Books *b) {
struct Books c = *a; /* backup first book */
*a = *b; /* replace first book with second book */
*b = c; /* replace second book with the backup of first book */
}
Then you should be able to use it like this:
if ( strcmp(book[i].title, book[i+1].title) < 0 ) {
swapBook( &book[i], &book[i+1] );
}
For more than two books, this is not going to work, you need to use qsort.
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
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.
I'm writing a code for a simple text based game, and when I purchase a car, the HP and TOPSPEED are registering for integers different than specified.
I've looked over the code myself, perhaps I'm not seeing it, but the Dodge Intrepid should register at 214hp and 140mph top speed, however when I enter the race menu, it registers for 320hp and 160mph top speed, which are the settings of the Mitsubishi 3000GT and the Dodge Stealth of the last beta. I imported the "race" code from the previous beta, being careful to omit any information about the cars used in the previous beta. If you can find my mistake or point anything out, it would be greatly appreciated (I'm including the code with my post). Thanks for your time. (I'm probably overlooking something) (Written in C, compiled and linked with DevC++)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*HP at RACE is malfunctioning, look over code.*/
int rnd(int range);
void seedrnd(void);
int main()
{
char name[15];
char ocar;
char exit;
char partsA;
char partsB;
char partsC;
char choice;
char dealer;
char model;
int bhp;
int ohp;
int tspd;
int otspd;
int score;
int oscore;
int cash;
int bonus;
int parts1;
int parts2;
int parts3;
int car1;
int car2;
int car3;
int car;
int hp1;
int hp2;
int hp3;
int tspd1;
int tspd2;
int tspd3;
printf("What is your name?\n");
scanf("%s",name);
parts1=1;
parts2=1;
parts3=1;
hp1=214;
tspd1=140;
hp2=490;
tspd2=190;
hp3=320;
tspd3=160;
car=0;
car1=0;
car2=0;
car3=0;
cash=40000;
while(exit!='-')
{
printf("\nMenu:\n1.Garage\n2.Race\n3.Parts Shop\n4.Dealerships\n\n");
choice=getch();
if(choice=='1')
{
printf("Welcome to %s's garage:\n\n",name);
if(car1>0)
{
printf("1.Dodge Intrepid\n");
}
if(car2>0)
{
printf("2.1988 Vector M12\n");
}
if(car3>0)
{
printf("3.Mitsubishi 3000GT\n");
}
car=getch();
if(car=='1')
{
if(car1>0)
{
printf("You are now driving a Dodge Intrepid\n");
car=1;
}
if(car1<1)
{
printf("You do not yet own this vehicle\n");
}
}
if(car=='2')
{
if(car2>0)
{
printf("You are now driving a 1988 Vector M12\n");
car=2;
}
if(car2<1)
{
printf("You do not yet own this vehicle\n");
}
}
if(car=='3')
{
if(car3>0)
{
printf("You are now driving a Mitsubishi 3000GT\n");
car=3;
}
if(car<1)
{
printf("You do not yet own this vehicle\n");
}
}
}
if(choice=='2')
{
if(car=1)
{
bhp=hp1;
tspd=tspd1;
}
if(car=2)
{
bhp=hp2;
tspd=tspd2;
}
if(car=3)
{
bhp=hp3;
tspd=tspd3;
}
/*Begin Race Mechanism*/
printf("Your selected car has %dhp and %dmph top speed\n\n",bhp,tspd);
printf("Now choose your opponent:\n");
printf("1.Rachel (150-250hp 110-130mph)\n");
printf("2.Kyle (250-350hp 130-170mph)\n");
printf("3.Darrian (350-450hp 170-210mph)\n");
printf("4.Chelsea (450-550hp 210-220mph)\n");
ocar=getch();
seedrnd();
if(ocar=='1')
{
ohp=rnd(100)+151;
otspd=rnd(20)+111;
bonus=500;
}
else if(ocar=='2')
{
ohp=rnd(100)+251;
otspd=rnd(40)+131;
bonus=1000;
}
else if(ocar=='3')
{
ohp=rnd(100)+351;
otspd=rnd(40)+171;
bonus=1500;
}
else if(ocar=='4')
{
ohp=rnd(100)+451;
otspd=rnd(10)+211;
bonus=2000;
}
else
{
printf("Haha, you're racing Eli\nNo contest here\n");
ohp=2;
otspd=25;
}
printf("Match-up:%s %dhp %dmph top speed\n",name,bhp,tspd);
printf(" vs \n");
printf("Opponent: %dhp %dmph top speed\n",ohp,otspd);
getch();
score=bhp*tspd;
oscore=ohp*otspd;
printf("Let the race begin\n");
sleep(1000);
printf("3\n");
sleep(1000);
printf("2\n");
sleep(1000);
printf("1\n");
sleep(1000);
printf("!\n\n");
sleep(2000);
printf("The race is over, and the winner is!!!\n\n\n\n");
sleep(3000);
if(score>oscore)
{
printf("YOU!!!\n");
cash=cash+(bonus);
}
else if(score<oscore)
{
printf("Your Opponent...\n");
}
else
{
printf("...neither of you, it was a tie!\n");
cash=cash+(bonus/2);
}
printf("You now have$%d.\n\n",cash);
}/* Closes choice 2*/
if(choice=='3')
{
/* Parts Shop*/
printf("Under Construction\n");
}
if(choice=='4')
{
printf("Press 'y' to exit\n");
printf("Please Select a Dealership\n");
printf("1.Dodge\n2.Vector\n3.Mitsubishi\n\n");
while(dealer!='y')
{
dealer=getch();
if(dealer=='1')
{
printf("DODGE:\n");
if(car1<1)
printf("1.Dodge Intrepid (214hp 140mph) $21,000\n\n");
model=getch();
if(model=='1')
{
if(cash<21000)
{
printf("You cannot afford this vehicle\n\n");
}
if(cash>=21000)
{
if(car1>0)
{
printf("You have already purchased this vehicle\n\n");
}
if(car1<1)
{
car1=car1+1;
cash=cash-21000;
printf("Thank You for purchasing this Dodge Intrepid\n\n");
}
}
}
}
if(dealer=='2')
{
printf("VECTOR:\n");
if(car2<1)
printf("1.1988 Vector M12 (490hp 190mph)$180,000\n\n");
model=getch();
if(model=='1')
{
if(cash<180000)
{
printf("You cannot afford this vehicle\n\n");
}
if(cash>=180000)
{
if(car2>0)
{
printf("You have already purchased this vehicle\n\n");
}
if(car2<1)
{
car2=car2+1;
cash=cash-180000;
printf("Thank You for purchasing this 1988 Vector M12\n\n");
}
}
}
}
if(dealer=='3')
{
printf("MITSUBISHI:\n");
if(car3<1)
printf("1.Mitsubishi 3000GT (320hp 160mph) $60,000\n\n");
model=getch();
if(model=='1')
{
if(cash<60000)
{
printf("You cannot afford this vehicle\n\n");
}
if(cash>=60000)
{
if(car3>0)
{
printf("You have already purchased this vehicle\n\n");
}
if(car3<1)
{
car3=car3+1;
cash=cash-60000;
printf("Thank You for purchasing this Mitsubishi 3000GT\n\n");
}
}
}
}
}
}
exit=getch();
}
return(0);
}
int rnd(int range)
{
int i;
i=rand()%range;
return(i);
}
void seedrnd(void)
{
srand((unsigned)time(NULL));
}
if(car=1)
{
bhp=hp1;
tspd=tspd1;
}
You probably mean if( car == 1 ) { ... this just sets car to 1, and "returns" 1 to the if. Then you do the same for car == 2 and car == 3.
= is the Assignment operator, while == is the comparison operator! The first assigns a value to a variable, while the latter returns true if the are the same (note, for char* you need strcmp()).
Generally you should break your program into small functions and also check for the unhappy case (e.g. what happens if user inputs something not acceptable?)
Another thing that you should pay some attention to is this
scanf("%s",name);
what if someone types in more than 15 characters? You will start righting in memory you do not own and this invokes Undefined Behaviour. One easy trick for that is to do
scanf("%14s", name);
This will restrict the input to 14 characters (and will keep the 15th for the nul terminator). Read more here: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
As others have noted in the comments, consider using structs to make your life easier. I haven't read the program in too detail to understand the exact structure of your game, but you could have for example a struct for the user:
struct player
{
char name[15];
car* owned_cars; //Linked List!
}
Where car is defined like that:
struct car
{
int max_speed;
int colour; //or even better an enum here
int seats;
//... etc.
car* next_car; //Make the Linked List's next node here!
}
Also! If you make a LinkedList, one mistake that usually happens is that they forgot to initialize thieir pointers to NULL. So :
car* new_car = malloc( sizeof(car) );
new_car->next_car = NULL;
If you don't do that, next_car will contain a random/garbage number! So when you try to go through the List
while(new_car->next_car != NULL)
{
//....
}
You will access memory you do not own.
Good luck and have fun!
There's also an issue in the following code:
if(car=='3')
{
if(car3>0)
{
printf("You are now driving a Mitsubishi 3000GT\n");
car=3;
}
if(car<1) // SHOULD BE car3<1
{
printf("You do not yet own this vehicle\n");
}
}
The integer distribution is wrong, because
int rnd(int range)
{
int i;
i=rand()%range;
return(i);
}
is wrong. That ought to be
int rnd(int range)
{
return rand() / ( RAND_MAX / range + 1 );
}
Read more here: Eternally Confuzzled: using rand()
Edit to the comment:
With this, I specifically respond to your question integer distribution error: the random distribution will not be uniform. Meaning, some numbers will appear significantly less frequently than others, not the property of a true (pseudo) random sequence.
The linked article contains more elaborate explanation of precisely what happens.
You are using the rnd() function defined at the bottom of in quite some places, and to be honest I haven't gone through all the code to understand the implications on what the program does, so I don't know whether it also answers some of the other questions you (vaguely) desscribe in the OP.
This section:
if(car=1)
{
bhp=hp1;
tspd=tspd1;
}
if(car=2)
{
bhp=hp2;
tspd=tspd2;
}
if(car=3)
{
bhp=hp3;
tspd=tspd3;
}
You are assigning car to 1, then 2, then 3: Use == instead of =.