Well I have only learnt C programming for 2 months. The code I got here is to solve a cashier system. I got some bar code number, item name and price. After cashier types in a numbers of bar codes and finishes with F, a receipt with item number, code and price should be shown.
These are the codes I compiled. However, I can only type one bar code and the program crashed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
typedef struct goods
{
char goods_code[6];
char goods_descrip[20];
float price;
}goodtype;
goodtype goods[13];
strcpy(goods[0].goods_descrip, "Chicken");
strcpy(goods[0].goods_code, "00310");
goods[0].price = 35.00;
strcpy(goods[1].goods_descrip, "Pork");
strcpy(goods[1].goods_code, "00311");
goods[1].price = 20.50;
strcpy(goods[2].goods_descrip, "Beef");
strcpy(goods[2].goods_code, "00322");
goods[2].price = 45.00;
strcpy(goods[3].goods_descrip, "Fish");
strcpy(goods[3].goods_code, "00323");
goods[3].price = 40.00;
strcpy(goods[4].goods_descrip, "Walmart T Shirt");
strcpy(goods[4].goods_code, "00510");
goods[4].price = 75.00;
strcpy(goods[5].goods_descrip, "Walmart Trousers");
strcpy(goods[5].goods_code, "00511");
goods[5].price = 120.00;
strcpy(goods[6].goods_descrip, "Walmart Coat");
strcpy(goods[6].goods_code, "00512");
goods[6].price = 100.00;
strcpy(goods[7].goods_descrip, "Walmart Jumper");
strcpy(goods[7].goods_code, "00513");
goods[7].price = 85.00;
strcpy(goods[8].goods_descrip, "Mug");
strcpy(goods[8].goods_code, "00710");
goods[8].price = 15.50;
strcpy(goods[9].goods_descrip, "Fry Pan");
strcpy(goods[9].goods_code, "00711");
goods[9].price = 200.00;
strcpy(goods[10].goods_descrip, "Bowl");
strcpy(goods[10].goods_code, "00712");
goods[10].price = 25.00;
strcpy(goods[11].goods_descrip, "Dish");
strcpy(goods[11].goods_code, "00713");
goods[11].price = 25.00;
char tempCode[6];
char receiptNM[20], receiptCD[6];
char stop[2] = {"F"};
float receiptPC, ttlcost = 0;
unsigned int i;
printf("Please enter the item code. Type F to finish");
scanf("%s", &tempCode);
while ( strcmp(tempCode, stop) ){
for (i = 0; i <= 12; ++i){
if (strcmp(tempCode, goods[i].goods_code) == 0){
strcpy(receiptNM, goods[i].goods_descrip);
strcpy(receiptCD, goods[i].goods_code);
receiptPC = goods[i].price;
ttlcost += goods[i].price;
}
else{
printf("This item code does not exist! Try again!\n");
}
printf("Please enter the item code. Type F to finish");
scanf("%s", &tempCode);
}
printf("_____________________________________\n\n");
printf(" THANK YOU FOR VISITING US! \n");
printf("_____________________________________\n");
printf(" Here is your receipt: \n\n");
printf("%10s%20s%10s", "Item", "Code", "Price");
printf("%10s%20s%10.2f\n", receiptNM, receiptCD, receiptPC);
printf("\n_____________________________________\n");
printf(" TOTAL COST:%.2f \n", ttlcost);
}
I'm struggling with this for hours and cannot fix it out.
An example output should beSample receipt
When I type 00310, the program cannot recognize it. While as I type 310 it can.
Also, when the code typed does not exist, the error message should only display once. But in my programm, it does 12 times.
You have made couple of mistakes. Let me point out them:-
First one pointed by Keine Lust: https://stackoverflow.com/a/40690102/3959321, where you're accessing memory out of bounds of array by iterating to 12 (inclusive). If you've declared an array of 12 elements, the indices range from 0 to 11 and not 0 to 12
for (i = 0; i <= 12; ++i){ //wrong iterations (< 12 should be here)
if (strcmp(tempCode, goods[i].goods_code) == 0) {
strcpy(receiptNM, goods[i].goods_descrip);
strcpy(receiptCD, goods[i].goods_code);
receiptPC = goods[i].price;
ttlcost += goods[i].price;
}
else {
printf("This item code does not exist! Try again!\n");
}
printf("Please enter the item code. Type F to finish");
scanf("%s", &tempCode);
}
Your program definitely will print "This item code doesn't exist!..." 12 times, as the else part is associated with an if and nested inside a for loop.
So, it will be called each time when item is not found for 12 iterations of the loop.
The correct program is:-
---- //Rest above is same
unsigned int i;
printf("Please enter the item code. Type F to finish");
scanf("%s", tempCode);
while ( strcmp(tempCode, stop) ) {
for (i = 0; i < 12; ++i){
if (strcmp(tempCode, goods[i].goods_code) == 0){
strcpy(receiptNM, goods[i].goods_descrip);
strcpy(receiptCD, goods[i].goods_code);
receiptPC = goods[i].price;
ttlcost += goods[i].price;
break;
}
}
if (i==12) //The loop iteration is complete, and i becomes 12 only when the for above hasn't been breaked (same as item found)
printf("This item code does not exist! Try again!\n");
printf("Please enter the item code. Type F to finish");
memset(tempCode,'\0',sizeof(tempCode));
scanf("%s", tempCode);
}
You are also making a mistake in the final reciept part:-
printf("%10s%20s%10s", "Item", "Code", "Price");
printf("%10s%20s%10.2f\n", receiptNM, receiptCD, receiptPC); //receiptNM, receiptCD and receiptPC are only single character arrays.
They will store only one string unlike your expectation. In order to store all of them you make an array of a structure (that contains item code, name of item, and price). Follow GumBoy's answer:-
https://stackoverflow.com/a/40690211/3959321
Here
for (i = 0; i <= 12; ++i){
if (strcmp(tempCode, goods[i].goods_code) == 0){
You are accessing to uninitialized values in the last iteration (undefined behaviour), because you just filled from goods[0] to goods[11]:
strcpy(goods[11].goods_descrip, "Dish");
strcpy(goods[11].goods_code, "00713");
goods[11].price = 25.00;
Looking at your output image. You are going to need a for loop to print out the values. In your current program the value of receiptCD, reciptNM and recieptPC are being replaced every time the condition in your if statement is met. I think you need to add another typedef struct for your receipts.
I fixed a few problems, but you are almost there. The last thing is of the justification of the text.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
typedef struct goods
{
char goods_code[6];
char goods_descrip[20];
float price;
}goodtype;
goodtype goods[13];
strcpy(goods[0].goods_descrip, "Chicken");
strcpy(goods[0].goods_code, "00310");
goods[0].price = 35.00;
strcpy(goods[1].goods_descrip, "Pork");
strcpy(goods[1].goods_code, "00311");
goods[1].price = 20.50;
strcpy(goods[2].goods_descrip, "Beef");
strcpy(goods[2].goods_code, "00322");
goods[2].price = 45.00;
strcpy(goods[3].goods_descrip, "Fish");
strcpy(goods[3].goods_code, "00323");
goods[3].price = 40.00;
strcpy(goods[4].goods_descrip, "Walmart T Shirt");
strcpy(goods[4].goods_code, "00510");
goods[4].price = 75.00;
strcpy(goods[5].goods_descrip, "Walmart Trousers");
strcpy(goods[5].goods_code, "00511");
goods[5].price = 120.00;
strcpy(goods[6].goods_descrip, "Walmart Coat");
strcpy(goods[6].goods_code, "00512");
goods[6].price = 100.00;
strcpy(goods[7].goods_descrip, "Walmart Jumper");
strcpy(goods[7].goods_code, "00513");
goods[7].price = 85.00;
strcpy(goods[8].goods_descrip, "Mug");
strcpy(goods[8].goods_code, "00710");
goods[8].price = 15.50;
strcpy(goods[9].goods_descrip, "Fry Pan");
strcpy(goods[9].goods_code, "00711");
goods[9].price = 200.00;
strcpy(goods[10].goods_descrip, "Bowl");
strcpy(goods[10].goods_code, "00712");
goods[10].price = 25.00;
strcpy(goods[11].goods_descrip, "Dish");
strcpy(goods[11].goods_code, "00713");
goods[11].price = 25.00;
char tempCode[6];
typedef struct receipt
{
char receiptNM[20], receiptCD[6];
float receiptPC;
}receipttype;
receipttype receipt[13];
char stop[2] = {"F"};
float ttlcost = 0;
unsigned int i;
unsigned int count = 0;
while ( strcmp(tempCode, stop) ){
printf("Please enter the item code. Type F to finish: ");
scanf("%s", tempCode);
for (i = 0; i <= 12; ++i){
if (strcmp(tempCode, goods[i].goods_code) == 0){
strcpy(receipt[count].receiptNM, goods[i].goods_descrip);
strcpy(receipt[count].receiptCD, goods[i].goods_code);
receipt[count].receiptPC = goods[i].price;
ttlcost += goods[i].price;
count++;
}
}
}
printf("_____________________________________\n\n");
printf(" THANK YOU FOR VISITING US! \n");
printf("_____________________________________\n");
printf(" Here is your receipt: \n\n");
printf("%10s%20s%10s", "Item", "Code", "Price\n");
for (int j= 0; j < count; ++j){
printf("%10s%20s%10.2f\n", receipt[j].receiptNM, receipt[j].receiptCD, receipt[j].receiptPC);
}
printf("\n_____________________________________\n");
printf(" TOTAL COST:%.2f \n", ttlcost);
}
Since nobody else mentioned it, here's a better way to fill in the array of structs.
typedef struct
{
char *code;
char *description;
float price;
}goodtype;
static goodtype goods[] =
{
{ "00310", "Chicken" , 35.00 },
{ "00311", "Pork" , 20.50 },
{ "00322", "Beef" , 45.00 },
{ "00323", "Fish" , 40.00 },
{ "00510", "T Shirt" , 75.00 },
{ "00511", "Trousers", 120.00 },
{ "00512", "Coat" , 100.00 },
{ "00513", "Jumper" , 85.00 },
{ "00710", "Mug" , 15.50 },
{ "00711", "Fry Pan" , 200.00 },
{ "00712", "Bowl" , 25.00 },
{ "00713", "Dish" , 25.00 }
};
static int goodscount = sizeof(goods) / sizeof(goods[0]);
int main( void )
{
for ( int i = 0; i < goodscount; i++ )
printf( "%3d %s %s\n", i, goods[i].code, goods[i].description );
printf( "Number of items: %d\n", goodscount );
}
There are several advantages to doing it this way:
It takes less typing, reducing the chance for human error
Saves a little memory, since you don't need to guess how big the code and description arrays need to be.
Avoids the possibility of buffer overrun (e.g. if you guessed wrong about the length of the strings).
Saves a little time, since you don't need to do all those strcpys.
Automatically counts the number of entries in the array, so you can't get that wrong.
Related
Right now this function is deleting the last name given by the user from a list, but I need it to delete all the names that match the name given by the user, not just the first occurrence of the user input, and need to free up allocated memory of the names that got deleted. How can I do this?
int deleteR(char**Fname,char **Lname,float *score,int count)
{
int i=0,j=0;
char *Lastname;
printf("\n Enter the Last Name of the Student you would like to delete from the records. ");
Lastname = (char *)malloc(15 * sizeof(char));
printf("\nLast Name: ");
scanf("%s",Lastname);
int counter = count;
for(i=0;i<count-1;i++)
{
if(strcmp(Lname[i],Lastname)==0)
{
for(j=i;j<count;j++)
{
Lname[j]=Lname[j+1];
Fname[j]=Fname[j+1];
score[j]=score[j+1];
}
counter--;
}
}
count=counter;
return count;
}
In case your loop on j remove entries because you do not change count later in a loop on i you will access values already checked and may freed because removed
You also have a memory leak because you allocate memory for Lastname but you never free it, and in fact there is no reason to not have Lastname as an array in the stack. Also your scanf can write out of Lastname without limit in size.
You do not need to have two embedded loops as you do, only one is enough to move entries managing an index to write and an other to read :
int deleteR(char**Fname, char **Lname, float *score, int count)
{
char lastname[16];
printf("\nEnter the Last Name of the Student you would like to delete from the records: ");
if (scanf("%15s", lastname) == 1) {
int i;
/* that first loop to search if the lastname is present */
for (i = 0; i < count; ++i) {
if (!strcmp(Lname[i], lastname)) {
/* at least present one time, update lists */
int futureCount = count - 1;
int j;
/* it seems you want to free removed resources */
free(Lname[i]);
free(Fname[i]);
/* that loop to move useful elements */
for (j = i + 1; j < count; ++j) {
if (strcmp(Lname[j], lastname)) {
/* still usefull */
Lname[i] = Lname[j];
Fname[i] = Fname[j];
score[i] = score[j];
i += 1;
}
else {
/* useless */
/* it seems you want to free removed resources */
free(Lname[j]);
free(Fname[j]);
futureCount -= 1;
}
}
return futureCount;
}
}
}
else
puts("EOF");
return count;
}
Using that main function to check :
int main()
{
char * fname[5];
char * lname[5];
float score[5];
int count, i;
fname[0] = strdup("Wolfgang Amadeus");
lname[0] = strdup("Mozart");
score[0] = 0;
fname[1] = strdup("Johann Sebastian");
lname[1] = strdup("Bach");
score[1] = 1;
fname[2] = strdup("Leopold");
lname[2] = strdup("Mozart");
score[2] = 2;
fname[3] = strdup("Johann Christian");
lname[3] = strdup("Bach");
score[3] = 3;
fname[4] = strdup("Ludwig van");
lname[4] = strdup("Beethoven");
score[4] = 4;
count = deleteR(fname, lname, score, 5);
printf("new lists:\n");
for (i = 0; i != count; ++i)
printf("%s %s : %g\n", fname[i], lname[i], score[i]);
return 0;
}
Compilation and executions :
pi#raspberrypi:/tmp $ gcc -Wall d.c
pi#raspberrypi:/tmp $ ./a.out
Enter the Last Name of the Student you would like to delete from the records: Chopin
new lists:
Wolfgang Amadeus Mozart : 0
Johann Sebastian Bach : 1
Leopold Mozart : 2
Johann Christian Bach : 3
Ludwig van Beethoven : 4
pi#raspberrypi:/tmp $ ./a.out
Enter the Last Name of the Student you would like to delete from the records: Mozart
new lists:
Johann Sebastian Bach : 1
Johann Christian Bach : 3
Ludwig van Beethoven : 4
pi#raspberrypi:/tmp $
I need to store data from a tournament. I need to know how many teams will play(n) and the number of games they will play (n!). Then, the team's names and their results. Something like this:
Input:
3 6
TeamX
TeamY
TeamZ
TeamX 0 - TeamY 3
TeamX 1 - TeamZ 0
TeamY 1 - TeamX 0
TeamY 0 - TeamZ 0
TeamZ 0 - TeamX 0
TeamZ 3 - TeamY 1
The output will be something like:
This winner is TeamY, with 7 point(s)
Won 2 game(s), tied 1 game(s) e lost 1 game(s)
Scored 5 goal(s) e suffered 3 goal(s)
EDIT2:
THIS is what I have until now. But it won't work at the scanf.... I can't type the team's names after the number of teams and games. Can you run it and try to understand?
Guide: I have game and team structs, first I add team names to theTeams array of structs, then I add the games to the games array of structs. Then, if/else blocks to do the maths of wins, losses, etc and finally see and printf the winner.
#include <stdio.h>
#include <string.h>
struct game {
const char *teamA;
int scoreA;
const char *teamB;
int scoreB;
};
struct team {
const char *teamA;
int score;
int wins;
int losses;
int ties;
int scored;
int suff;
};
struct team team_new(const char *teamA, int score, int wins, int losses, int ties, int scored, int suff)
{
struct team t;
t.teamA = strdup(teamA);
t.score = score;
t.wins = wins;
t.losses = losses;
t.ties = ties;
t.scored = scored;
t.suff = suff;
return t;
};
struct game game_new(const char *teamA, int scoreA, const char *teamB, int scoreB)
{
struct game g;
g.teamA = strdup(teamA);
g.scoreA = scoreA;
g.teamB = strdup(teamB);
g.scoreB = scoreB;
return g;
};
int main(void)
{
int i, j, teams, nrgames, biggestScore, whichTeam;
scanf("Teams and number of games %d %d", &teams, &nrgames);
//add team names to theTeamss struct
struct team theTeams[teams];
size_t num_teams = 0;
for (i = 0; i < teams; ++i)
{
char teamA[20];
if (scanf("%s", teamA) != 1)
exit(0);
theTeams[++num_teams] = team_new(teamA, 0, 0, 0, 0, 0, 0);
}
struct game games[nrgames]; //add games
size_t num_games = 0;
for (i = 0; i < sizeof games / sizeof *games; ++i)
{
char teamA[20], teamB[20];
int scoreA, scoreB;
if (scanf(" %s %d - %s %d", teamA, &scoreA, teamB, &scoreB) != 4)
exit(0);
games[++num_games] = game_new(teamA, scoreA, teamB, scoreB);
}
//run through games[] to change values of theTeams[] scores
//games - A against B
for (i = 0; i < sizeof games / sizeof *games; ++i)
{
for (j = 0; j < sizeof theTeams / sizeof *theTeams; ++j)
{
if ((games[i].teamA == theTeams[j].teamA)) //team(A)
{
//if A wins
if(games[i].scoreA > games[i].scoreB)
{
theTeams[j].score += 3;
theTeams[j].wins += 1;
theTeams[j].scored = games[i].scoreA;
}
//if A loses
else if (games[i].scoreA < games[i].scoreB)
{
theTeams[j].score += 0;
theTeams[j].losses += 1;
theTeams[j].suff = games[i].scoreB;
}
else //tied
{
theTeams[j].score += 1;
theTeams[j].ties += 1;
theTeams[j].suff = games[i].scoreA;
}
}
if ((games[i].teamB == theTeams[j].teamA))//team(B)
{
//if B wins
if(games[i].scoreB > games[i].scoreA)
{
theTeams[j].score += 3;
theTeams[j].wins += 1;
theTeams[j].scored = games[i].scoreB;
}
//if B loses
else if (games[i].scoreB < games[i].scoreA)
{
theTeams[j].score += 0;
theTeams[j].losses += 1;
theTeams[j].suff = games[i].scoreA;
}
else //tied
{
theTeams[j].score += 1;
theTeams[j].ties += 1;
theTeams[j].suff = games[i].scoreB;
}
}
}
}
//accessing to the winner team
biggestScore = theTeams[0].score;
whichTeam = 0;
for (i = 0; i < sizeof theTeams / sizeof *theTeams; ++i){
if (theTeams[i].score > biggestScore){
biggestScore = theTeams[i].score;
whichTeam = i;
}
}
//output
printf("\n This winner is %s, with %d point(s), Won %d game(s), tied %d game(s) and lost %d game(s), Scored %d goal(s) e suffered %d goal(s)\n", theTeams[whichTeam].teamA, theTeams[whichTeam].score, theTeams[whichTeam].wins, theTeams[whichTeam].losses, theTeams[whichTeam].ties, theTeams[whichTeam].scored, theTeams[whichTeam].suff);
return 0;
}
There are no "problems" with C language and strings; you can do whatever you want. It's just a bit more responsibility than in other languages.
You seem to need an array of structures, yes. I would recommend modelling it as just an array of games played, where each game records the teams that took part, and their scores. No need to first record a list of "available" teams, it's easier to just extract that from the game data afterwards.
struct game {
const char *teamA;
int scoreA;
const char *teamB;
int scoreB;
};
struct game game_new(const char *teamA, int scoreA, const char *teamB, int scoreB)
{
struct game g;
g.teamA = strdup(teamA);
g.scoreA = scoreA;
g.teamB = strdup(teamB);
g.scoreB = scoreB;
return g;
}
and then in the man program:
int main(void)
{
struct game games[100];
size_t num_games = 0;
for (size_t i = 0; i < sizeof games / sizeof *games; ++i)
{
char teamA[100], teamB[100];
int scoreA, scoreB;
if (scanf(" %s %d - %s %d", teamA, &scoreA, teamB, &scoreB) != 4)
break;
games[++num_games] = game_new(teamA, scoreA, teamB, scoreB);
}
}
C like all programming languages is only as good as the plan you have laid out to model the data
For this, an array of arrays that stores the data can work.
Might want to also consider a database for relationships based on teams. Then you can also add metadata and the like (for example, timestamps). Though its only good if you don't mind externalising application beyond C.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This code take input from the user (characters C,T,B) and (int 0-24 and 0-60) to calculate the cost of parking based on the type of vehicle the user inputs.
the last line of code in the program is supossed to print the result of the function "charged" which is determined by the type of vehicle declared by the user inputed char value but when i run it only retruns 0.00 instead of the flaot value any and all help is appreciated :)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int total_minute_parked (int minute_in, int minute_left)
{
int minute_parked;
if (minute_in > minute_left)
{
minute_parked = (minute_left - minute_in + 60);
}
else
{
minute_parked = (minute_left - minute_in);
}
return minute_parked;
}
// func calc total hours parked
int total_hour_parked (int hour_in, int hour_left)
{
int hours_parked;
if (hour_left > hour_in)
{
hours_parked = abs((hour_left - 1) - hour_in);
}
else
{
hours_parked = abs(hour_left - hour_in);
}
return hours_parked ;
}
// -------------------funtion to calc charge based off type of vehicle------
float charged (char vehicle_type,int total_hour_parked)
{
char C;
char T;
char B;
float temp_charged;
if (vehicle_type == C) // -------------------------------CAR
{
if (total_hour_parked > 3)
{
float secondary_hour = total_hour_parked - 3;
temp_charged = secondary_hour * 1.5;
}
else
{
temp_charged = 0;
}
}
else if (vehicle_type == T) // ------------------------------TRUCK
{
if (total_hour_parked > 2)
{
float secondary_hour = total_hour_parked - 2;
temp_charged = (secondary_hour * 2.3) + 1.0;
}
else {
temp_charged = 1;
}
}
else if (vehicle_type == B) // -----------------------------------BUS
{
if (total_hour_parked > 1)
{
float secondary_hour = total_hour_parked - 1;
temp_charged = (secondary_hour * 3.7) + 2.0;
}
else {
temp_charged = 2;
}
}
return temp_charged;
}
//---------------------- end program upon invalid imput -------------------//
// --------------------- main that prints results and takes imput -----------//
int main()
{
int total_hour_parked (int hour_in,int hour_left);
float charged (char vehicle_type, int total_hour_parked);
char vehicle_type;
int hour_in = 0;
int minute_in = 0;
int hour_left = 0;
int minute_left = 0;
printf("Please enter the type of Vehicle:");
scanf("%c",&vehicle_type);
printf("Please enter the hour entered lot:");
scanf("%d", &hour_in);
printf("Please enter the minute entered lot:");
scanf("%d", &minute_in);
printf("Please enter the hour left lot:");
scanf("%d", &hour_left);
printf("Please enter the minute left lot:");
scanf("%d", &minute_left);
printf("------------------------------------\n");
printf("Parking time: %d:%d\n", total_hour_parked(hour_in,hour_left),total_minute_parked(minute_in,minute_left));
printf("Cost %f",charged(vehicle_type,total_hour_parked));
return 0;
}
I'm not sure if it's going to solve all the problems in the code, but there's an issue here:
char C;
char T;
char B;
float temp_charged;
if (vehicle_type == C) // -------------------------------CAR
What this does is it declares three char and doesn't assign any value (so accessing them is undefined and will result in some rubbish value). Then you are comparing vehicle_type against those chars. The result will most likely be false (or 0). That's not what you intended. Instead, do this:
if (vehicle_type == 'C')
You probably misunderstood what char C; means. It doesn't mean "make a char with value 'C'", but "make a char named C and don't initialize it". But in this scenario you don't need those three chars anyway bcause you can just compare vehicle_type with a literal.
Their are several problems in the above code.
1). You are comparing vehicle_type with the char which are not assign so first assign the values to this char variables
char C = 'C';
char T = 'T';
char B = 'B';
Or you can directly compare like
if (vehicle_type == 'T')
2). total_hour_parked is a function not a integer variable so what you can do is store the return value of total_hour_parked in any variable
Eg:-
int m_total_hour_parked = total_hour_parked(hour_in, hour_left);
printf("Parking time: %d:%d\n", m_total_hour_parked, total_minute_parked(minute_in, minute_left));
printf("Cost %f", charged(vehicle_type, m_total_hour_parked));
Hopefully that helps
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my code, I'd like to use string that denotes Will, Bob, Billy, Ryan or Ed instead of int. Specifically, using N strings S[1],S[2]...S[N] where S[I] the names above.
And also, input N is limited as following: (1 ≤ N ≤ 100,000)
#include <stdio.h>
int main(void)
{
int input_num=0;
int isWill = 0;
int isBob = 0;
int isBilly = 0;
int isRyan = 0;
int isEd = 0;
int n=0;
scanf("%d", input_num);
printf("%d", input_num);
for(n;n<input_num;n++)
{
char tmp[100,000];
scanf("%s", tmp);
if(tmp == "Will")
isWill = 1;
else if(tmp == "Bob")
isBob = 1;
else if(tmp == "Billy")
isBlue = 1;
else if(tmp == "Ryan")
isRyan = 1;
else if(tmp == "Ed")
isEd = 1;
}
//end of input
if(isWill == 0)
printf("Will\n");
if(isBob == 0)
printf("Bob\n");
if(isBilly == 0)
printf("Billy\n");
if(isRyan == 0)
printf("Ryan\n");
if(isEd == 0)
printf("Ed\n");
return 0;
}
To compare strings, you need to use the strcmp library function, which returns 0 if the two argument strings are equal:
if ( strcmp( tmp, "Will" ) == 0 )
// tmp contains the string "Will"
If you want an array of strings, you can do it one of two ways. You can declare a 2d array, where the first dimension is tne number of names, and the second dimension is the max length of a name:
char names[NUMBER_OF_NAMES][MAX_NAME_LENGTH+1];
To copy a string, use strcmp:
strcmp( names[0], "Will" );
strcmp( names[1], "Bob" );
// etc.
Or, you can declare a 1D array, where each element is a pointer to a string:
char *names[NUMBER_OF_NAMES];
names[0] = "Will";
names[1] = "Bob";
Note that you're assigning a pointer value to names[i]; you're not copying the string contents to names[i].
Finally, C doesn't recognize integer literals like 100,000; you'll want to declare your tmp buffer as
char tmp[100000];
although that's somewhat large for a string buffer.
Several things not quite as i would write them.
I had some minutes to spare and wrote a compiling example.
Maybe your problems can be solved by this.
char * colortext[] =
{
"unknown",
"white",
"black",
"blue",
"red",
"yellow"
};
typedef enum color {
unknown = 0,
white,
black,
blue,
red,
yellow
};
typedef struct
{
int number;
char name[200];
color team;
}Player;
typedef struct
{
char * name;
color team;
}Autoassign;
Autoassign autoassign[] =
{
{"Will", white},
{"Bob", black},
{"Billy", blue},
{"Ryan", red},
{"Ed", yellow}
};
int autoassignLength = sizeof(autoassign) / sizeof(autoassign[0]);
int Player_print(Player * player)
{
int e = 0;
printf("\n");
printf("Player %i Profile:\n", player->number);
printf("Name: '%s'\n", player->name);
printf("Team: '%s'\n", colortext[player->team]);
printf("\n");
return e;
}
int Player_scan(Player * player, int number)
{
int e = 0;
int i;
printf("Input Player Name: ");
scanf("%s", player->name);
player->number = number;
player->team = unknown;
for(i = 0; i < autoassignLength; ++i)
{
if(0 == strcmp(player->name,autoassign[i].name))
{
player->team = autoassign[i].team;
break;
}
}
return e;
}
int main(int argc, char ** argv)
{
int i;
int input_num, n;
Player players[10];
printf("How many Players? ");
scanf("%d", &input_num);
for(n = 0; n < input_num ; n++)
{
Player_scan(&players[n], n+1);
}
for(n = 0; n < input_num ; n++)
{
Player_print(&players[n]);
}
return 0;
}
If you want to make compare strings that's not the way to go.
Use string.h library to be able to use the function strcmp .
To use this functions type strcmp(string1, string2)
Just remember that strcmp will return 0 if the strings are equal.
So what you want to do is use if(!strcmp("Will", tmp)) to enter the if when the strings are the same.
You also need to change char tmp[100,000] to char tmp[100000], for this is the supported format in C.
Hope this helps.
I am getting unexpected results from my bubble sort program in C.
The program below is a program which takes 5 inputs from the user, performs selection sort on them, then performs exchange sort on them.
If i use these inputs:
50
150
75
175
23
It should sort them to the following:
23
50
75
150
175
However, it doesnt sort correctly and sorts like the following (opposite way around for exchange as it does it in Descending order):
150
175
23
50
75
Its quite strange because if you enter certain values it will sort them correctly such as:
73
84
03
26
83
Not quite sure whats going on with it. I cant start making changes to it when it technically works for certain values.
I must be missing something somewhere.
Any help would be appreciated.
CODE IN FULL:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
int main(int argc, char *argv[])
{
char arc5Strings[5][256];
int nCount, nCount2, nCount3, nCount4, nCount5, nCount6, nCount7, letter, sorted;
int fMinVal[1][2] = {1,1};
int nMinValPosition;
int nMoves;
int nRow;
int i, j, k, indexOfCurrentSmallest, q, temp;
char arcTemp[256];
int nOutOrder;
int nNumValues;
int clean1, clean2;
//input the values
for(nCount=0; nCount < 5; nCount++)
{
printf("Please input string %d/5: ", nCount + 1);
fgets(arc5Strings[nCount], 256, stdin);
if(strlen(arc5Strings[nCount]) > 11)
{
printf("Your string contains more than 10 characters. Please try again.");
nCount = 5;
exit(0);
}
}
//------------------------------------------------------------------------------
//Selection Sort
printf("\n\n");
for(i=0;i<5;i++)
{
indexOfCurrentSmallest = i;
for(j=i;j<5;j++)
{
for(k=0;k<255;k++)
{
if(arc5Strings[j][k] < arc5Strings[indexOfCurrentSmallest][k])
{
//we found a new possible smallest
indexOfCurrentSmallest = j;
break;
}
else if(arc5Strings[j][k] > arc5Strings[indexOfCurrentSmallest][k])
{
//no point in searching further, the one we are looking at is already larger than the one we found.
break;
}
}
}
//let's do a swap
for(q=0;q<255;q++)
{
temp = arc5Strings[i][q];
arc5Strings[i][q] = arc5Strings[indexOfCurrentSmallest][q];
arc5Strings[indexOfCurrentSmallest][q] = temp;
}
}
//---------------------------------------------------------------
//print entire array
printf("This is your selection sorted array based on ASCII values\n\n");
for(nCount3 = 0; nCount3 < 5; nCount3++)
{
for(nCount4 = 0; arc5Strings[nCount3][nCount4] != '\0'; nCount4++)
{
printf("%c", arc5Strings[nCount3][nCount4]);
}
}
//---------------------------------------------------------------------
//Exchange Sort
nNumValues = 5;
nOutOrder = TRUE;
nMoves = 0;
while(nOutOrder && nNumValues > 0)
{
nOutOrder = FALSE;
for(i=0;i<5;i++)
{
for(nCount=0; nCount < nNumValues -1; nCount++)
{
for(nCount2=0, sorted=0; sorted==0; nCount2++)
{
if(arc5Strings[nCount][nCount2] < arc5Strings[nCount+1][nCount2])
{
for(letter=0; letter<256; letter++)
{
arcTemp[letter] = arc5Strings[nCount][letter];
}
for(letter=0; letter<256; letter++)
{
arc5Strings[nCount][letter]= arc5Strings[nCount+1][letter];
}
for(letter=0; letter<256; letter++)
{
arc5Strings[nCount+1][letter] = arcTemp[letter];
}
sorted = 1;
nMoves++;
}
else if (arc5Strings[nCount][nCount2] < arc5Strings[nCount+1][nCount2])
sorted = 1;
}
}
nNumValues--;
}
}
printf("\n\n\nThe sorted list in Descending order is: \n\n\n");
for(nCount5 = 0; nCount5 < 5; nCount5++)
{
printf("%s", arc5Strings[nCount5]);
}
//-----------------------------------------------
printf("\n %d moves were required to sort this list\n\n", nMoves);
return 0;
}
It's because you're sorting strings rather than numbers, so it's using character-based sorting.
In other words, "175" is less than "23" because "1" is less than "2".
If you want to sort them as numbers, convert them to numbers first.
You are using strings while you should be using integers. Either convert your string to integer or use int straight away
See this link an example if you want to compare string
compare two alphanumeric string
Again use Array of integers if you dont need text as an input to compare