Sorting/Swaping/File(i/o)_withStrings Struct Arrays

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 610 Views - Last Post: 03 December 2013 - 07:15 AM Rate Topic: -----

#1 sporte00  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 26-November 13

Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 26 November 2013 - 08:47 PM

Attached File  general_morehead.txt (4.07K)
Number of downloads: 23

Attached File  restaurants.txt (3.02K)
Number of downloads: 17

At the moment I was asked to build a program that can build a set of "Meals" that fit a users give caloric and cost parameters.

What i have gotten it to do is the following:
-build a struct of arrays
-take users settings and any food that they want the meal to start with
-I can also get it to print this data out

What i cannot get it to do is properly:
--sort
--swap
--filter struct arrays for future "Possible meals"

I have however been able to get a different program that follows similar guidelines using struct arrays. This program that is functioning is called restaurants. However in that program I am only sorting the data. What I'd like to do is present both of these codes to anyone in the forum, and ask these four questions:

1.)Why the data is not passing in the manner that I'm expecting in the "Future meals" program, but it is in the restaurant cost program."
2.)Would it have been more effective to use pointers?
3.)Would it have been more effective to use swap and sort from <algorithm>?
4.)In the code "Restaurants" I was able to manipulate the data using a bubble sort function, but i had trouble using ifstream to get the strings into the structure. Any direction on this would be most appreciative
5.)I have been using a massive custom ".h" file that has any and all possible includes statements from any previous and future assignments. Could someone explain to me why it's bad code practice, and what i could do to shrink its size.


The error I'm getting is specifically from output.h.

Fore warning: In no way am i proud of how bloated this code has become.


#include "General_MoreHead.h"
using namespace std;

struct mark {
	   char   *n;
       int    ca;                                                   
       double co; 
	   int    key;
	   int    oof;
};
struct listeds{
	double costs;
	int    calo;
	int    fk;
	int    picked;
};
struct plan{
	int k0;
	int k1;
	int k2;
	int k3;
	double totalcost;
	int totalcalories;

};
void run(void);
void print(void);
void PrintMenu_and_MenuInstructions(struct mark a[],struct mark b[],struct mark c[],struct mark d[]);
void U_P1( struct listeds men[],struct mark mas[]);
void U_P2(struct listeds men[],struct mark mas[]);
void build1(struct mark a[],struct mark b[],struct mark c[],struct mark d[], struct mark mas[]);
void build2(struct listeds men[]);
void wrt1(struct mark d[], int size);
void wrt2(struct listeds d[], int size);
void wrt3(struct plan d[], int size);
void passiveremoval(struct listeds men[], int mealcount, struct plan meal[], struct mark mas[] );
void build3(struct plan meal[], int k);
int  mascalref(struct mark mas[], int k);
double  mascosref(struct mark mas[], int k);
void condense(struct listeds menu[],  struct plan meal[], struct mark mas[] );


void PrintMenu_and_MenuInstructions(struct mark a[],struct mark b[],struct mark c[],struct mark d[]){ 
		wrt1(a,5);
		wrt1(b,5);
		wrt1(c,5);
		wrt1(d,5);
		printf("%s",
		"________________________________________________________________________________"
		"==============================Meal Planner 10K=================================="
		"-Directions: \n"
		"    1.)Specify the most money you're willing to spend.                          "
		"    2.)Specify the maximum amount of calories you're willing to consume.        "
		"    3.)Pick the number of food items that you want in your meal                 "
		"    4.)Specify the food items that you want in your meal with out going over the"
		"       number that you just set in step four.                                   "
		"    5.)You must pick atleast one food to put in your meal yourself.             "

		"-Please note: \n"
		"    a.)The total combination of the priciest items is $6.79.                    "
		"    b.)You can only buy one item from each type of food group.                  "
		"    c.)If you pick all of you food items then the program will not make a list. "
		"       of five other possible menus from the choices youve made.                "
		"    d.)Our menu is low calorie, but cators to your cal. limits.                 "
		"    d.)If you need assistance find some.                                        "
		"================================================================================"
		"________________________________________________________________________________" 
		);
}
void wrt1(struct mark d[], int size){
		for(int i = 0; i < size; i++)	{	
			printf("[%1.d] %s||cost: $ %.2f || %.f Cal.  \n", d[i].key, d[i].n, d[i].co, d[i].ca );}
}
void wrt2(struct listeds d[], int size){
		for(int i = 0; i < size; i++)	{	
			printf("\n%1.2f   %d cal %d fk  %d picked ",d[i].costs, d[i].calo, d[i].fk, d[i].picked );}
}
void wrt3(struct plan d[], int size){
		for(int i = 0; i < size; i++)	{	
			printf("\nMeal[%1.d]| cost: $ %.2f || %1.d Cal.||\n ||[%1.d] k0||[%1.d] k1||[%1.d] k2||[%1.d] k3||  ", i, d[i].totalcost, d[i].totalcalories, d[i].k0, d[i].k1, d[i].k2, d[i].k3 );}
}
void U_P1(struct listeds men[],struct mark mas[]){	

	int k,c,d;
	double b,kid;
	youreAnorexic:
	//get the amount of money the user is going to spend with error check
	printf("\n%s"," How much money do you wish spend:  ");
	b=isnum();
			if (b > 1.25){ 
				men[4].costs=b;
				printf("...  Remember any amount of money paid over the max of $6.79 is kept as tip.\n");
				goto nextone1;}
			else if(b < 1.25){
				printf("\n...  You are now starving...  That is too small of a number.\n");
				goto youreAnorexic;}

	nextone1:
	printf("%s","________________________________________________________________________________");


	//get the amount of calories the user is going to spend with error check
	youreFAT:
	printf("\n%s"," How many callories do you wish to consume: " );
	c =isnum();
		if (c > 2000){
			printf("\n...  You are now fat...  That is too great of a number.");
			men[4].calo=c;
			goto youreFAT;}
		else if(c < 351){
			printf("\n...  You are now starving...  That is too small of a number.");
			goto youreFAT;}
		else {men[4].calo=c;};
		
	printf("%s","________________________________________________________________________________");
	
	//get the number of foods the user would like to pick for themselves with error checking
	yourWrong:
	printf("\n%s"," Of the four food types offered how many would you like to choose yourself?",
				  "\n (Type a number x where: 0 <= x <= 4) ");
		d=isnum();
		if (d > 4){
			printf("That is too great of a number.\n");
			goto yourWrong;}
		else if(d < 5) {
			men[4].fk = d;
			k=d;
			}

	printf("%s","________________________________________________________________________________");
}
void U_P2(struct listeds men[],struct mark mas[]){
	
	int k,totalcal,kid;
	double b,c,d,totalcost;
	//get the foods the user would like to pick for themselves with error checking
	k = men[4].fk;
	
	figureitoutalready:
	printf("\n%s"," Pick your choices by typing their food# in the space below.",k ,
				  "\n (Type only numbers less than 20 and they must be one from each foodgroup) ");
		for(int i=0; i < k ;++i){
			youmakemylifeharderthanitneedstobe:
			kid = isint();
			//check if the food key number exists and if the food group its in was already chosen
				if(men[0].fk > 20){
					printf("That food does not exist on the menu\n");
					goto youmakemylifeharderthanitneedstobe;
					}
				if(lt5a(kid) == 0){
					if(men[0].picked == 0){
						men[0].fk = kid;
						men[0].costs  = mas[kid].co;
						men[0].calo = mas[kid].ca;
						men[0].picked = 1;
						goto cleard;}
					else if(men[0].picked==1){
						printf("You cannot pick the a food from the same group twice\n"); 
						goto youmakemylifeharderthanitneedstobe;}
					}
				else if(gt5lt10a(kid) == 0){
					if(men[1].picked == 0){
						men[1].fk = kid;
						men[1].costs  = mas[kid].co;
						men[1].calo = mas[kid].ca;
						men[1].picked = 1;
						goto cleard;}
					else if(men[1].picked == 1){
						printf("You cannot pick the a food from the same group twice\n"); 
						goto youmakemylifeharderthanitneedstobe; }
					}
				else if(gt10lt15a(kid) == 0){
					if(men[2].picked == 0){
						men[2].fk = kid;
						men[2].costs  = mas[kid].co;
						men[2].calo = mas[kid].ca;
						men[2].picked = 1;
						goto cleard;}
					else if(men[2].picked == 1){
						printf("You cannot pick the a food from the same group twice\n"); 
						goto youmakemylifeharderthanitneedstobe; }
					}
				else if(gt15lt20a(kid) == 0){
					if(men[3].picked == 0){
						men[3].fk = kid;
						men[3].costs  = mas[kid].co;
						men[3].calo = mas[kid].ca;
						men[3].picked = 1;
						goto cleard;}
					else if(men[3].picked == 1){
						printf("You cannot pick the a food from the same group twice\n"); 
						goto youmakemylifeharderthanitneedstobe;}
					}
		cleard:
			totalcost = ((men[0].costs)+(men[1].costs)+(men[2].costs)+(men[3].costs));
			totalcal  = ((men[0].calo)+(men[1].calo)+(men[2].calo)+(men[3].calo));
			men[5].calo  = totalcal;
			men[5].costs = totalcost;
			printf("|| subtotal cost: %1.2f  ||calories: %2d ||\n",totalcost,totalcal);

		//check to see if they're total calories and cost do not go over what they said it should be
			if( totalcost > men[4].costs ){
				printf("That combo costs more than you can pay\n");
				printf("%s","________________________________________________________________________________");
				goto youmakemylifeharderthanitneedstobe;}
			else if(totalcal > men[4].calo){
				printf("That food combo has more calories than you specified.\n");
				printf("%s","________________________________________________________________________________");
				goto youmakemylifeharderthanitneedstobe;}
			else{}	

		
		}

	//change the boolean for the items that have been picked so that search doesnot repick
	for(int n=0; n < men[4].fk ; ++n){
		if( men[n].fk < 20){
			mas[men[n].fk].oof= 0;}
			}
};
void build1(struct mark a[],struct mark b[],struct mark c[],struct mark d[], struct mark mas[]){
	//Build Food Blocks

			char	*veggie[5]=				{"Carrots            ","Lettuce           ","Celery            ","Spinach           ","Broccoli          "};
			double  veggie_costs[5]=		{.69, .20, .42, .40, .50 };
			int     veggie_callories[5]=	{25,5,6,7,50};
			int     v_key[5]=				{0,1,2,3,4};
			int     Omni_onOff[5] =         {1,1,1,1,1};
			char	*fruit[5]=				{"Blueberries       ","Cherrie           ","Peaches           ","Grapes            ","Pineapple         "};
			double  fruit_costs[5] =		{1.75, 1.1, .92, .82, .50};
			int     fruit_callories[5] =	{85,77,59,62,225};
			int     f_key[5]=				{5,6,7,8,9};
			char	*protien[5]=			{"Pork             ","Beef             ","Chicken          ","A Vegan          ","Soylent          "};
			double  protien_costs[5]=		{1.9, 2.1, .85, 0, 1.2};
			int     protien_callories[5]=	{147,390,306,500, 350};
			int     p_key[5]=				{10,11,12,13,14};
			char	*carb[5]=				{"Pasta            ","Whole Grain Bread","Brown Rice       ","Potato           ","Beer             "};
			double  carb_costs[5]=			{1, .55, .75, 1.25, 2.25 };
			int     carb_callories[5]=		{390,140,216,163,154};
			int     c_key[5]=				{15,16,17,18,19};


		 mas[20].n   = "Air";
		 mas[20].ca  = 0;
		 mas[20].co  = 0;
		 mas[20].key = 0;
		 mas[20].oof = 1;

	for(int i=0;i<5;++i){
		 mas[i].n   = veggie[i];
		 mas[i].ca  = veggie_callories[i];
		 mas[i].co  = veggie_costs[i];
		 mas[i].key = v_key[i];
		 mas[i].oof = Omni_onOff[i];
		 a[i].n   = veggie[i];
		 a[i].ca  = veggie_callories[i];
		 a[i].co  = veggie_costs[i];
		 a[i].key = v_key[i];
		 a[i].oof = Omni_onOff[i];	

		 int o1 = 5;
		 mas[i+o1].n   = fruit[i];
		 mas[i+o1].ca  = fruit_callories[i];
		 mas[i+o1].co  = fruit_costs[i];
		 mas[i+o1].key = f_key[i];
		 mas[i+o1].oof = Omni_onOff[i];
		 b[i].n   = fruit[i];
		 b[i].ca  = fruit_callories[i];
		 b[i].co  = fruit_costs[i];
		 b[i].key = f_key[i];
		 b[i].oof = Omni_onOff[i];

		 int o2 = 10;
		 mas[i+o2].n   = protien[i];
		 mas[i+o2].ca  = protien_callories[i];
		 mas[i+o2].co  = protien_costs[i];
		 mas[i+o2].key = p_key[i];
		 mas[i+o2].oof = Omni_onOff[i];
		 c[i].n   = protien[i];
		 c[i].ca  = protien_callories[i];
		 c[i].co  = protien_costs[i];
		 c[i].key = p_key[i];
		 c[i].oof = Omni_onOff[i];

		 int o3 = 15;
		 mas[i+o3].n   = carb[i];
		 mas[i+o3].ca  = carb_callories[i];
		 mas[i+o3].co  = carb_costs[i];
		 mas[i+o3].key = c_key[i];
		 mas[i+o3].oof = Omni_onOff[i];
		 d[i].n   = carb[i];
		 d[i].ca  = carb_callories[i];
		 d[i].co  = carb_costs[i];
		 d[i].key = c_key[i];
		 d[i].oof = Omni_onOff[i];}
}
void build2(struct listeds menu[],int k){
		for(int i=0;i<k;++i){
		 menu[i].calo = (1/1)-1;
		 menu[i].costs  = (1/1)-1;
		 menu[i].fk = 20;
		 menu[i].picked = (1/1)-1;}

}
void build3(struct plan meal[], int k){
	for(int i=0;i<k;++i){
		 meal[i].k0 = 20;
		 meal[i].k1 = 20;
		 meal[i].k2 = 20;
		 meal[i].k3 = 20;
		 meal[i].totalcost  = 0;
		 meal[i].totalcalories = 0;}
}
double  mascosref(struct mark mas[], int k){
	double seeker;

	seeker = mas[k].co;

return seeker;
}
int     mascalref(struct mark mas[], int k){
	int seeker;

	seeker = mas[k].ca;

return seeker;
}
void run(void){
	int z=0,builder=4;
	struct mark veg[5];
	struct mark car[5];
	struct mark fru[5];
	struct mark pro[5];
	struct mark master[21];
	struct plan mealplan[10];
	struct listeds menu[6];
	build3(mealplan, builder);
	build1(veg, fru, pro, car, master);
	build2(menu, 6);

//	PrintMenu_and_MenuInstructions(veg, fru, pro, car);

	wrt3(mealplan, builder);

	U_P1(menu, master);
	U_P2(menu, master);
	//block search

	printf("\n How many meals would you like me to plan?\n type no more than three");
	builder = isint();
	condense(menu, mealplan, master);
	//passiveremoval(menu, builder, mealplan, master);
	
	wrt3(mealplan, builder);
}
void condense(struct listeds menu[], struct plan meal[], struct mark master[]){
// VEGGIES///////////////////////////////////////////////////////////////////

	if(menu[0].picked==1){
			int n,n2;
			double n1;
			n  = menu[0].fk;
			n1 = meal[0].totalcost;
			n2 = meal[0].totalcalories;
			meal[0].totalcost = (n1+ master[n].co);
			meal[0].totalcalories =(n2 + master[n].ca);
			meal[0].k0 = menu[0].fk;}
	else if(menu[0].picked==0){
			int n,n2;
			double n1;
			n  = master[0].key;
			meal[0].totalcost = (n1+ master[n].co);
			meal[0].totalcalories =(n2 + master[n].ca);
			meal[0].k0 = menu[0].fk;}

// FRUIT/////////////////////////////////////////////////////////////////////
																																				//// fruit/////////////////////////////////////////////////////////////////////
	if(menu[1].picked==1){
		int n,n2;
		double n1;
		n  = menu[1].fk;
		n1 = meal[0].totalcost;
		n2 = meal[0].totalcalories;
		meal[0].totalcost = (n1+ master[n].co);
		meal[0].totalcalories =(n2 + master[n].ca);
		meal[0].k1 = menu[1].fk;}
	else if(menu[0].picked==0){
			int n,n2;
			double n1;
			n  = master[0].key;
			meal[0].totalcost = (n1+ master[n].co);
			meal[0].totalcalories =(n2 + master[n].ca);
			meal[0].k1 = menu[8].fk;}
// PROTIEN///////////////////////////////////////////////////////////////////
	if(menu[2].picked==1){
		int n,n2;
		double n1;
		n  = menu[2].fk;
		n1 = meal[0].totalcost;
		n2 = meal[0].totalcalories;
		meal[0].totalcost = (n1+ master[n].co);
		meal[0].totalcalories =(n2 + master[n].ca);
		meal[0].k2 = menu[2].fk;}
	else if(menu[0].picked==0){
			int n,n2;
			double n1;
			n  = master[0].key;
			meal[0].totalcost = (n1+ master[n].co);
			meal[0].totalcalories =(n2 + master[n].ca);
			meal[0].k2 = menu[13].fk;}
// CARBOHYDRATES/////////////////////////////////////////////////////////////
	if(menu[0].picked==1){
		int n,n2;
		double n1;
		n  = menu[3].fk;
		n1 = meal[0].totalcost;
		n2 = meal[0].totalcalories;
		meal[0].totalcost = (n1+ master[n].co);
		meal[0].totalcalories =(n2 + master[n].ca);
		meal[0].k3 = menu[n].fk;}	
	else if(menu[0].picked==0){
		int n,n2;
		double n1;
		n  = master[0].key;
		meal[0].totalcost = (n1+ master[n].co);
		meal[0].totalcalories =(n2 + master[n].ca);
		meal[0].k3 = menu[18].fk;}

}
void passiveremoval(struct listeds menu[], int mealcount, struct plan meal[], struct mark mas[] ){
	int RANDMAXXx=6;
	int kid;

	for(int i =0; i < mealcount*4; ++i){
			kid = menu[i].fk;
			printf("\n%d || %d || %d || %d\n",lt5a(kid),gt5lt10a(kid),gt10lt15a(kid),gt15lt20a(kid));
			

						}
			if(kid = 20){
				ans=1;
																																																																																																																																																															//// VEGGIES///////////////////////////////////////////////////////////////////
				if((meal[mealcount].k0) == 20){
					int n,n2,count=0, temptotalcal;
					double n1, temptotalcos;
					//all iterations will begin here
					again1000:
						if(count < RANDMAXXx){
						n2 = shuffler(4);
						temptotalcos = mascosref(mas, n2)+ meal[mealcount].totalcost ;
						temptotalcal = mascalref(mas, n2)+ meal[mealcount].totalcalories ;
						int n3,item2;
						double item;
						n1 = mascosref(mas, mas[n2].key);
						n3 = mascalref(mas, mas[n2].key);
						
						if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==1){
							int d;
							d=count;
							count= d+1;
							goto again1000;}
						else if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==2){
							int d;
							d=count;
							count= d+1;
							goto again1000;}
						else if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==0){
							meal[mealcount].k0 = mas[n2].key;
							item2 = meal[mealcount].totalcalories;
							item = meal[mealcount].totalcost;
							meal[mealcount].totalcost = (n1+ item);
							meal[mealcount].totalcalories = (n3+ item2);
								
								}
							}
					 else if(count >= RANDMAXXx){
					 		meal[mealcount].k0 = 1;
								
					 }
					}
// FRUIT/////////////////////////////////////////////////////////////////////
				else if((meal[mealcount].k1) == 20){
					int n,n2,count=0,temptotalcal;
					double n1, temptotalcos;
					//all iterations will begin here
					again0100:
						if(count < RANDMAXXx){
							n2 = 5+shuffler(4);
							n1 = mascosref(mas, mas[n2].key);
							temptotalcos= mascosref(mas, meal[mealcount].k0)+mascosref(mas, n2)+mascosref(mas, meal[mealcount].k2)+ mascosref(mas, meal[mealcount].k3);
							temptotalcal=mascalref(mas, meal[mealcount].k0)+mascalref(mas, n2)+mascalref(mas, meal[mealcount].k2)+ mascalref(mas, meal[mealcount].k3);
						int n3,item2;
						double item;
						n1 = mascosref(mas, mas[n2].key);
						n3 = mascalref(mas, mas[n2].key);
						
						if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==1){
							int d;
							d=count;
							count= d+1;
							goto again0100;}
						else if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==2){
							int d;
							d=count;
							count= d+1;
							goto again0100;}
						else if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==0){
							meal[mealcount].k1 = mas[n2].key;
							item2 = meal[mealcount].totalcalories;
							item = meal[mealcount].totalcost;
							meal[mealcount].totalcost = (n1+ item);
							meal[mealcount].totalcalories = (n3+ item2);
								
								}
							}
					 else if(count >= RANDMAXXx){
					 		meal[mealcount].k1 = 1;
								
					 }
					}
// PROTIEN///////////////////////////////////////////////////////////////////
				else if((meal[mealcount].k2) == 20){
					int n,n2,count=0,temptotalcal;
					double n1, temptotalcos;
					//all iterations will begin here
					again0010:
						if(count < RANDMAXXx){
							n2 = 10+shuffler(4);
							n1 = mascosref(mas, mas[n2].key);
							temptotalcos= mascosref(mas, meal[mealcount].k0)+mascosref(mas, meal[mealcount].k1)+mascosref(mas, n2)+ mascosref(mas, meal[mealcount].k3);
							temptotalcal=mascalref(mas, meal[mealcount].k0)+mascalref(mas, meal[mealcount].k1)+mascalref(mas, n2)+ mascalref(mas, meal[mealcount].k3);
						int n3,item2;
						double item;
						n1 = mascosref(mas, mas[n2].key);
						n3 = mascalref(mas, mas[n2].key);
						
						if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==1){
							int d;
							d=count;
							count= d+1;
							goto again0010;}
						else if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==2){
							int d;
							d=count;
							count= d+1;
							goto again0010;}
						else if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==0){
							meal[mealcount].k2 = mas[n2].key;
							item2 = meal[mealcount].totalcalories;
							item = meal[mealcount].totalcost;
							meal[mealcount].totalcost = (n1+ item);
							meal[mealcount].totalcalories = (n3+ item2);
								
								}
							}
					 else if(count >= RANDMAXXx){
					 		meal[mealcount].k2 = 1;
							 
					 }
					}
// CARBOHYDRATES/////////////////////////////////////////////////////////////
				else if((meal[mealcount].k3) == 20){
					int n,n2,count=0,item,temptotalcal;
					double n1, temptotalcos;
					//all iterations will begin here
					again0001:
						if(count < RANDMAXXx){
							n2 = 15+shuffler(4);
							n1 = mascosref(mas, mas[n2].key);
							temptotalcos= mascosref(mas, meal[mealcount].k0)+mascosref(mas, meal[mealcount].k1)+mascosref(mas, meal[mealcount].k2)+ mascosref(mas, n2);
							temptotalcal=mascalref(mas, meal[mealcount].k0)+mascalref(mas, meal[mealcount].k1)+mascalref(mas, meal[mealcount].k2)+ mascalref(mas, n2);
							int n3,item2;
							double item;
							n1 = mascosref(mas, mas[n2].key);
							n3 = mascalref(mas, mas[n2].key);
						
								if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==1){
									int d;
									d=count;
									count= d+1;
									goto again0001;}
								else if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==2){
									int d;
									d=count;
									count= d+1;
									goto again0001;}
								else if((greater(temptotalcos, menu[4].costs) + greater(temptotalcal, menu[4].calo))==0){
									meal[mealcount].k3 = mas[n2].key;
									item2 = meal[mealcount].totalcalories;
									item = meal[mealcount].totalcost;
									meal[mealcount].totalcost = (n1+ item);
									meal[mealcount].totalcalories = (n3+ item2);}
							}
						else if(count >= RANDMAXXx){meal[mealcount].k3 = 1;}
					}
				}
			}
int  main(void){
    int r,d;
	again:



	system("CLS");
	run();

    cout <<"\n\n Again? \n Yes = 1 and No = 0: ";
    cin >> r;
    cout <<"\n";

    if(r==1){goto again;}

    return 0;
};


Is This A Good Question/Topic? 0
  • +

Replies To: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

#2 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,124
  • Joined: 05-May 12

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 26 November 2013 - 11:17 PM

OMG! Why do you have:
- all those goto's?
- all those parallel arrays?
- those terrible names for functions and structure members?
- horribly inconsistent indentation style?

View Postsporte00, on 26 November 2013 - 10:47 PM, said:

5.)I have been using a massive custom ".h" file that has any and all possible includes statements from any previous and future assignments. Could someone explain to me why it's bad code practice, and what i could do to shrink its size.


In general, you should only include the headers that you need. This is to speed up compile time. But with precompiled headers, fast machines, and SSDs, this argument for faster compiles feels like it is falling to the wayside.

View Postsporte00, on 26 November 2013 - 10:47 PM, said:

1.)Why the data is not passing in the manner that I'm expecting in the "Future meals" program, but it is in the restaurant cost program."
2.)Would it have been more effective to use pointers?
3.)Would it have been more effective to use swap and sort from <algorithm>?
4.)In the code "Restaurants" I was able to manipulate the data using a bubble sort function, but i had trouble using ifstream to get the strings into the structure. Any direction on this would be most appreciative


I cannot even find where the "Future meals" program or "restaurant cost" program is in your source code. Ctrl-F to find was failing me. Can you tell us which line numbers those programs are at?
Was This Post Helpful? 2
  • +
  • -

#3 sporte00  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 26-November 13

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 27 November 2013 - 03:52 PM

I attached those in the text documents, because I realize that the "Meals" going to be a bit out of whack.

-As a side note i cleaned the "Meals program up a bit. Perhaps this version below will look a bit better




#include "General_MoreHead.h"
#define n 20
#define countmax 4000

using namespace std;
  
ifstream infile;

struct filedata{

	  int    calories;                                                   
      double cost;
	  int    id; 
	  char   *name;
	  int    OnOff;
}; 
void writeFileWrite(void);
void PrintMenu_and_MenuInstructions(void);
void U_P1(int Intake1[]);  
void wrt1(filedata d[]);
void squencingData(void);
void FoodPicker(filedata arr[], double arr1[], double intake[], int Range, int mealnumber, int count, int done[]);

void writeFileWrite(void){ 
		//create a text file in the project directory, and write to it. 
		string name = "25 .69\n5 .20\n6 .42\n7 .40\n50 .50\n85 1.75\n77 1.1\n59 .92\n62 .82\n225 .50\n147 1.9\n390 2.1\n306 .85\n500 0\n350 .12\n390 1\n140 .55\n216 .75\n163 1.25\n154 2.25";
		ofstream myfile; 
		myfile.open ("data.txt");
		myfile << name ; 
		myfile.close();
};
void PrintMenu_and_MenuInstructions( void){ 
		printf("%s",
		"________________________________________________________________________________"
		"==============================Meal Planner 10K=================================="
		"-Directions: \n"
		"    1.)Specify the most money you're willing to spend.                          "
		"    2.)Specify the maximum amount of calories you're willing to consume.        "
		"-Please note: \n"
		"    a.)The total combination of the priciest items is $6.79.                    "
		"    b.)Our menu is low calorie, but cators to your cal. limits.                 "
		"    c.)If you need assistance find some.                                        "
		"================================================================================"
		"________________________________________________________________________________" 
		);
}
void wrt1(filedata d[]){
		for(int i = 0; i < n; i++)	{	
			printf("[%1.d] %s||cost: $ %2.2f || %f Cal.  \n", d[i].id, d[i].name, d[i].calories, d[i].calories);}
} 
void U_P1(double Intake1[]){	

	int k,c,d;
	double b,kid;
	youreAnorexic:
	//get the amount of money the user is going to spend with error check
	printf("\n%s"," How much money do you wish spend");
	b=isdbl();
			if (b > 1.25){ 
				Intake1[0] = b;
				printf("...  Remember any amount of money paid over the max of $6.79 is kept as tip.\n");
				goto nextone1;}
			else if(b < 1.25){
				printf("\n...  You are now starving...  That is too small of a number.\n");
				goto youreAnorexic;}

	nextone1:
	printf("%s","________________________________________________________________________________");


	//get the amount of calories the user is going to spend with error check
	youreFAT:
	printf("\n%s"," How many callories do you wish to consume" );
	c =isdbl();
		if (c > 2000){
			printf("\n...  You are now fat...  That is too great of a number.");
			Intake1[0] = c;
			goto youreFAT;}
		else if(c < 351){
			printf("\n...  You are now starving...  That is too small of a number.");
			goto youreFAT;}
		
	printf("%s","________________________________________________________________________________");
} 
void FoodPicker(filedata arr[],double arr1[], double intake[], int Range, int mealnumber, int count, int done[]){

	int  fooda,foodb;
	if(Range == 5){
		printf("Range fail");
		int v1 =isint();		
		 Range=0; count =0;}
	else { 
			if(count == countmax ){  
				printf("countmax fail");
				int v1 =isint();
				FoodPicker(arr, arr1, intake, Range, mealnumber, count, done);}
			else {
				++count;
				if(Range==0){fooda = 4; foodb = 0;}
				else if( (Range)==1){foodb = 9;fooda =5;}
				else if( (Range)==2){foodb = 14;fooda =10;}
				else if( (Range)==3){foodb = 19;fooda =15;}

				int RandomNumber= rand()% fooda +foodb ;
					if(arr[RandomNumber].OnOff==0){
						printf("RandomNumber fail");
						int v1 =isint();
						FoodPicker(arr, arr1, intake, Range, mealnumber, count, done);}
					else {// get measures
						int totalCaloriesAvalible,ItemInQuestionCal,TempTotalCal;
						double CashInHand,ItemInQuestionCost,TempTotalCost;
						totalCaloriesAvalible  = intake[0];
						CashInHand = intake[1];
						ItemInQuestionCal = arr[RandomNumber].calories;
						ItemInQuestionCost = arr[RandomNumber].cost;
						TempTotalCal = arr1[mealnumber] +ItemInQuestionCal;
						TempTotalCost = arr1[mealnumber]  +ItemInQuestionCost;

							//check if the item is out of range
						if(gt0na(CashInHand-TempTotalCost) == 0 ){//out of range call yourself again
									FoodPicker(arr, arr1, intake, Range, mealnumber, count, done);}
						else if(gt0na(totalCaloriesAvalible-TempTotalCal) == 0){//out of range call yourself again
									FoodPicker(arr, arr1, intake, Range, mealnumber, count, done);}
						else { // use the randomly generated picked item
								if(Range==0){
									arr1[mealnumber]  = TempTotalCost;
									done[mealnumber]  = TempTotalCal;
									cout << "\nMeal set " << mealnumber << " \n[" <<  mealnumber << "] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n";
									arr[RandomNumber].OnOff==0; 
									++Range;
									FoodPicker(arr, arr1, intake, Range, mealnumber, count, done);}
								else if( (Range)==1){ 
									arr1[mealnumber] = TempTotalCost;
									done[mealnumber] = TempTotalCal;
									cout<<"[" << mealnumber+1 <<"] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n";
									arr[RandomNumber].OnOff==0; 
									++Range;
									FoodPicker(arr, arr1, intake, Range, mealnumber, count, done);} 
								else if( (Range)==2){ 
									arr1[mealnumber] = TempTotalCost;
									done[mealnumber] = TempTotalCal;
									cout <<"["<< mealnumber+2 <<"] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n";
									arr[RandomNumber].OnOff==0; 
									++Range;
									FoodPicker(arr, arr1, intake, Range, mealnumber, count, done);}
								else if( (Range)==3){ 
									arr1[mealnumber] = TempTotalCost;
									done[mealnumber] = TempTotalCal;
									cout << "["<< mealnumber+2 <<"] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n" 
										 << "     ||Total Cost: $ " <<TempTotalCost<<" || Total Calories" <<TempTotalCal <<" Cal.  \n" ;
									arr[RandomNumber].OnOff==0; 
									++Range;
									FoodPicker(arr, arr1, intake, Range, mealnumber, count, done);}}}
				 }
		 }
 }
void squencingData(void){

	struct filedata master[n];
		infile.open ("Data.txt");
	char	*names[20]=	 {"Carrots           ","Lettuce           ","Celery            ","Spinach           ","Broccoli          ","Blueberries       ","Cherrie           ","Peaches           ","Grapes            ","Pineapple         ","Pork             ","Beef             ","Chicken          ","A Vegan          ","Soylent          ", "Pasta            ","Whole Grain Bread","Brown Rice       ","Potato           ","Beer             "};


	if (infile.fail()){
		cerr << "Can't open file for input.\n";
		int d=isint();
		exit(1);}

	for(int d = 0; d < n; d++){ 
		infile		  >> master[d].calories;
		infile		  >> master[d].cost;
		}

	for(int d = 0; d < n; d++){ 
		master[d].name  =  names[d];
		master[d].id = d;	 
		master[d].OnOff = 1;}




		wrt1(master);	

	infile.close();
 
} 
int  main(void){
    int r;
	again:

	writeFileWrite();
 
	  
	squencingData();


    cout <<"\n\n Again? \n Yes = 1 and No = 0: ";
    cin >> r;
    cout <<"\n";

    if(r==1){goto again;}

    return 0;
};


Was This Post Helpful? 0
  • +
  • -

#4 sporte00  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 26-November 13

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 27 November 2013 - 03:59 PM

The parallel array's/gotos/random indents are my poor coding habbits comming through.
Was This Post Helpful? 0
  • +
  • -

#5 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,124
  • Joined: 05-May 12

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 27 November 2013 - 08:49 PM

View Postsporte00, on 26 November 2013 - 10:47 PM, said:

1.)Why the data is not passing in the manner that I'm expecting in the "Future meals" program, but it is in the restaurant cost program."


So with your updated code, where are you passing the data? What result are you getting? What was your expected result?
Was This Post Helpful? 0
  • +
  • -

#6 sporte00  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 26-November 13

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 28 November 2013 - 04:17 PM

So with your updated code, where are you passing the data? What result are you getting? What was your expected result?

The updated code is supposed to read the numbered data from a file, and then pass it to the recursive function called "FoodPicker". From here this function should loop until four food items from each food group are picked. Now I have been able to prove that the "FoodPicker"function in fact will both pick full sets of "meals," because at one point it pushed out four unique meals. Yet here is the kicker... Now the infile part of the program is not picking up the data correctly. To test this I would just have the program print out what the Master file would look like. To my dismay none of the data from the file was picked up. The program is not spitting up any errors unfortunately. Which tells me i may just have some kind of referencing error, or perhaps something needed to be initialized.


p.s. I believe in the recent publish of the code I did not have the "FoodPicker" function active.

I did take your point of the number of goto's to heart, and removed a vast majority of them.
Was This Post Helpful? 0
  • +
  • -

#7 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,124
  • Joined: 05-May 12

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 28 November 2013 - 08:13 PM

We are not psychic or clairvoyant. We can't read your mind or see what changes you made. Post your updated code.
Was This Post Helpful? 0
  • +
  • -

#8 sporte00  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 26-November 13

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 29 November 2013 - 02:22 PM

1.)Updated code
2.).h file

The problem is the same as before. The printf that displays the menu is still malfunctioning. Also I have the rest of the program working. So i guess I only need help fixing that.



1.)

#include "General_MoreHead.h"
#define twenty1 20
#define countmax 4000
#define two1  2
#define five1 5
using namespace std;
  
ifstream infile;

struct filedata{

	  int    calories;                                                   
      double cost;
	  int    id; 
	  char   *name;
	  int    OnOff;
}; 
void writeFileWrite(void);
void PrintMenu_and_MenuInstructions(void);
void U_P1(int Intake1[]);  
void wrt1(filedata d[]);
int squencingData(void);
int FoodPicker(filedata arr[], double arr1[], double intake[], int /*Range[]*/ Numberline , int mealnumber, int count, int done[]);

void writeFileWrite(void){ 
		//create a text file in the project directory, and write to it. 
		string name = "25 .69\n5 .20\n6 .42\n7 .40\n50 .50\n85 1.75\n77 1.1\n59 .92\n62 .82\n225 .50\n147 1.9\n390 2.1\n306 .85\n500 0\n350 .12\n390 1\n140 .55\n216 .75\n163 1.25\n154 2.25";
		ofstream myfile; 
		myfile.open ("data.txt");
		myfile << name ; 
		myfile.close();
};
void PrintMenu_and_MenuInstructions( void){ 
		printf("%s",
		"________________________________________________________________________________"
		"==============================Meal Planner 10K=================================="
		"-Directions: \n"
		"    1.)Specify the most money you're willing to spend.                          "
		"    2.)Specify the maximum amount of calories you're willing to consume.        "
		"-Please note: \n"
		"    a.)The total combination of the priciest items is $6.79.                    "
		"    b.)Our menu is low calorie, but cators to your cal. limits.                 "
		"    c.)If you need assistance find some.                                        "
		"================================================================================"
		"________________________________________________________________________________" 
		);
}
void wrt1(filedata d[]){
		for(int i = 0; i < twenty1; i++)	{	
			printf("[%1.d] %s||cost: $ %2.2f || %f Cal.  \n", d[i].id, d[i].name, d[i].calories, d[i].calories);}
} 
void U_P1(double Intake1[]){	

	int k,c,d;
	double b,kid;
	youreAnorexic:
	//get the amount of money the user is going to spend with error check
	printf("\n%s"," How much money do you wish spend");
	b=isdbl();
			if (b > 1.25){ 
				Intake1[0] = b;
				printf("...  Remember any amount of money paid over the max of $6.79 is kept as tip.\n");
				goto nextone1;}
			else if(b < 1.25){
				printf("\n...  You are now starving...  That is too small of a number.\n");
				goto youreAnorexic;}

	nextone1:
	printf("%s","________________________________________________________________________________");


	//get the amount of calories the user is going to spend with error check
	youreFAT:
	printf("\n%s"," How many callories do you wish to consume" );
	c =isdbl();
		if (c > 2000){
			printf("\n...  You are now fat...  That is too great of a number.");
			Intake1[0] = c;
			goto youreFAT;}
		else if(c < 351){
			printf("\n...  You are now starving...  That is too small of a number.");
			goto youreFAT;}
		
	printf("%s","________________________________________________________________________________");
} 
int FoodPicker(filedata arr[],double arr1[], double intake[], int /*Range[]*/ Numberline , int mealnumber, int count, int done[]){
	 
	if(/*Range[5]*/ Numberline == 5){
		printf("Range fail");
		int v1 =isint();		
		 /*Range[5]=0; Range[0]=0;*/Numberline=0; count =0; return 0;} 
	else { 
			if(count == countmax ){  
				printf("countmax fail");
				int v1 =isint();
				return (FoodPicker(arr, arr1, intake, /*Range*/ Numberline, mealnumber, count, done));}
			else {
				int  fooda ,foodb;
				++count;
				if(/*Range[0]==0*/ Numberline==0){fooda = 4; foodb = NULL;    goto NEXT;}
				else if(/*Range[1]*/ Numberline==1){fooda = 9;foodb =5;   goto NEXT;}
				else if( /*Range[2]*/ Numberline==2){fooda = 14;foodb =10; goto NEXT;}
				else if(/* Range[3]*/ Numberline==3){fooda = 19;foodb =15; goto NEXT;} 
				NEXT:
				int RandomNumber= rand()% fooda +foodb ;
				
					if(arr[RandomNumber].OnOff==0){
						printf("RandomNumber fail");
						int v1 =isint();
				return (FoodPicker(arr, arr1, intake, /*Range*/ Numberline, mealnumber, count, done));}
					else {// get measures
						int totalCaloriesAvalible,ItemInQuestionCal,TempTotalCal;
						double CashInHand,ItemInQuestionCost,TempTotalCost;
						totalCaloriesAvalible  = intake[0];
						CashInHand = intake[1];
						ItemInQuestionCal = arr[RandomNumber].calories;
						ItemInQuestionCost = arr[RandomNumber].cost;
						TempTotalCal = arr1[mealnumber] +ItemInQuestionCal;
						TempTotalCost = arr1[mealnumber]  +ItemInQuestionCost;

						//check if the item is out of range
						if(gt0na(CashInHand-TempTotalCost) <= 0 ){							//out of range call yourself again
									return(FoodPicker(arr, arr1, intake,  /*Range*/ Numberline, mealnumber, count, done));}
						else if(gt0na(totalCaloriesAvalible-TempTotalCal) <= 0){			//out of range call yourself again
									return(FoodPicker(arr, arr1, intake,  /*Range*/ Numberline, mealnumber, count, done));}
						else {														 // use the randomly generated picked item
								if(/*Range[0]==0*/ Numberline==0){				// VEGGIE STAGE
									arr1[mealnumber]  = TempTotalCost;
									done[mealnumber]  = TempTotalCal;
									cout << "\nMeal set " << mealnumber << " \n[" <<  mealnumber << "] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n";
									arr[RandomNumber].OnOff==0; 
									/*Range[0] = 1;
									Range[1] = 0;*/
									++Numberline;
									return(FoodPicker(arr, arr1, intake,  /*Range*/ Numberline, mealnumber, count, done));}
								else if( /*Range[1]*/ Numberline==1){		// FRUIT STAGE
									arr1[mealnumber] = TempTotalCost;
									done[mealnumber] = TempTotalCal;
									cout<<"[" << mealnumber+1 <<"] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n";
									arr[RandomNumber].OnOff==0; 
									/*Range[1] = 1;
									Range[2] = 0;*/
									++Numberline;
									return(FoodPicker(arr, arr1, intake,  /*Range*/ Numberline, mealnumber, count, done));} 
								else if( /*Range[2]*/ Numberline==2){ 
									arr1[mealnumber] = TempTotalCost;
									done[mealnumber] = TempTotalCal;
									cout <<"["<< mealnumber+2 <<"] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n";
									arr[RandomNumber].OnOff==0; 
									/*Range[2] = 1;
									Range[3] = 0;*/
									++Numberline;
									return(FoodPicker(arr, arr1, intake,  /*Range*/ Numberline, mealnumber, count, done));}
								else if( /* Range[3]*/ Numberline==3){ 
									arr1[mealnumber] = TempTotalCost;
									done[mealnumber] = TempTotalCal;
									cout << "["<< mealnumber+2 <<"] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n" 
										 << "     ||Total Cost: $ " <<TempTotalCost<<" || Total Calories" <<TempTotalCal <<" Cal.  \n" ;
									arr[RandomNumber].OnOff==0; 
									/*Range[3] = 1;
									Range[1] = 0;
									Range[5] = 1;*/
									++Numberline;
 									return(FoodPicker(arr, arr1, intake,  /*Range*/ Numberline, mealnumber, count, done));}}}
					
				}
		 } 
	/*delete [] Range;*/
	return 0;
}
int squencingData(void){

	struct filedata master[twenty1];
	infile.open ("Data.txt");
	char	*names[twenty1]=	 {"Carrots           ","Lettuce           ","Celery            ","Spinach           ","Broccoli          ","Blueberries       ","Cherrie           ","Peaches           ","Grapes            ","Pineapple         ","Pork             ","Beef             ","Chicken          ","A Vegan          ","Soylent          ", "Pasta            ","Whole Grain Bread","Brown Rice       ","Potato           ","Beer             "};
	double  intake[two1]={.01,.001}, MealPlanRecordedCosts[twenty1];
	int		Count=0;
	int		Mealnumber=0;
	int		MealPlanRecordedCalories[twenty1];
	//int		numberline[five1]={0,1,1,1,1};
	int		numberline=0;	
 
	if (infile.fail()){
		cerr << "Can't open file for input.\n";
		int d=isint();
		exit(1);}

	for(int d = 0; d < twenty1; d++){ 
		infile		  >> master[d].calories;
		infile		  >> master[d].cost;
		master[d].name  =  names[d];
		master[d].id = d;	 
		master[d].OnOff = 1;
		MealPlanRecordedCalories[d] =d;
		MealPlanRecordedCosts[d] = (double)d;}


		wrt1(master);						//prewrite of the foods to check if the file data got recorded
		PrintMenu_and_MenuInstructions();	//instructions
		U_P1(intake);						//get user data and place into an array: Intake[0]=maximum calories the user specifies
											//										 Intake[1]=maximum cash the user wishes to spend
		FoodPicker(master,MealPlanRecordedCosts, intake, numberline, Mealnumber, Count, MealPlanRecordedCalories);

	infile.close();
/*	delete [] numberline;*/
 return 0;
} 
int  main(void){
    int r;
	again:

	writeFileWrite();
 
	  
	squencingData();


    cout <<"\n\n Again? \n Yes = 1 and No = 0: ";
    cin >> r;
    cout <<"\n";

    if(r==1){goto again;}

    return 0;
};





2.)

#include <vector>
#include <cstring>
#include <iostream> 
#include <iomanip> 
#include <fstream>
#include <string> 
#include <cmath>
#include <cctype> 
#include <ctime> 
#include <cstdlib> 
#include <map>         
#include <algorithm> 
#include <utility>   
#include <bitset>  
#include <stack>   
#include <stdio.h>  
#include <stdlib.h>
#include <stddef.h>
#include <ctype.h>
#include <limits.h>
#include <time.h>         /* for time() */
#include <assert.h>
#include <sstream>
#include <conio.h>
#include <ostream>
#include <errno.h>


//Inefficient call list of Macros for universal code testing(V0.ch9):
#define SECONDS_PER_DAY (60*60*24)
#define PI 4.0*arctan(1.0)
#define C  299792.458
#define EOF (-1)
#define MAXINT 214783647
#define ITERS 50
#define SIZE 250
#define EPS 1.0e-9
#define min_2(x,y) (((x) < (y)) ? (x) : (y))
#define SQ(x) ((x)*(x))
#define max_2(x,y) (((x) > (y)) ? (x) : (y))
#define max_3(x,y,z) (((x) > (max_2(y,z))) ? (x) : (max_2(y,z)))

#define   shuffleswap(x, y)    { int t; t = x; x = y; y = t; }
#define   order(x, y)   if (x > y) shuffleswap(x, y)
#define   o2(x, y)      order(x, y)
#define   o3(x, y, z)   o2(x, y); o2(x, z); o2(y, z)

using namespace std;


#define lt5(x)       (((x) < (5)) ? (x):(1))
#define lt5a(x)      (((x) < (5)) ? (0):(1))
#define lt5n(x)      (((x) < (5)) ? (1):(x))
#define gt4(x)		 (((x) > (4)) ? (x):(1))
#define gt4a(x)		 (((x) > (4)) ? (0):(1))
#define gt5lt10(x)   (((gt4(x)) < (10)) ? (gt4(x)):(1))
#define gt5lt10a(x)  (((gt4(x)) < (10)) ? (gt4a(x)):(1))
#define gt9(x)		 (((x) > (9)) ? (x):(1))
#define gt9a(x)		 (((x) > (9)) ? (0):(1))
#define gt1na(x)	 (((x) > (-1)) ? (0):(1))

#define gt0na(x)	 (((x) > (0)) ? (0):(1))
#define greater(x,y) (((x) > (y)) ? (0):(1))
#define lessert(x,y)	 (((x) < (y)) ? (0):(1))
#define gt10lt15(x)  (((gt9(x)) < (15)) ? (gt9(x)):(1))
#define gt10lt15a(x) (((gt9(x)) < (15)) ? (gt9a(x)):(1))
#define gt14(x)		(((x) > (14)) ? (x):(1))
#define gt14a(x)	(((x) > (14)) ? (0):(1))
#define gt15lt20(x)  (((gt14(x)) < (20)) ? (gt14(x)):(1))
#define gt15lt20a(x) (((gt14(x)) < (20)) ? (gt14a(x)):(1))


//
//bool is_number(string src);
int  isOdd    (int integer);
int  shuffler(int k);
void randomize (int arr[], int n);
double  isnum(void);
int isint(void);


void randomize (int arr[], int n){
    srand ( time(NULL) );				
    for (int i = n-1; i > 0; i--){
        int j = rand() % (i+1);
        shuffleswap(arr[i], arr[j]);}}
int  isOdd( int integer ){
  if ( integer % 2== 0 )
     return 1;
  else
     return 2;
}
int  shuffler(int k,int y){
	int arr[100];
for(int i = y; i <k; i++){
		arr[i] = i;}
int n = sizeof(arr)/ sizeof(arr[0]);
	randomize (arr, n);

int	TherandomNumberReturned = arr[rand() % k+y];
return TherandomNumberReturned;
}
int isnumber(string src){
  const char *start = src.c_str();
 

  char *end;
  long string_value = strtol(start,&end,10);
  
  // Did we set off errno?
  // Is it too big?
  // Too small?
  // Non-numerics?
 
  if ( string_value > numeric_limits<int>::max() ||  numeric_limits<int>::min() > string_value   || static_cast<unsigned>(end - start) != src.length()) 
  {return 0;}
  return 1;
}
double isdbl(void){
  int d=0,n;
  redo:
  string s ;
  printf(": ");
  cin >> s;
		if(d == 5){
			exit(1);}
		else if(d<5){		
			double value = atof(s.c_str());
			if(value == 0){return 0;}
			else{
				if(gt1na(value) == 0){
					return value;}
				else if(gt1na(value) == 1){
					n=d+1;
					d=n;
					goto redo;}
				}
			}
		else {
			n=d+1;
			d=n;
			goto redo;
			}
}
int isint(void){
  int d=0,n;
  redo:
  string s ;
  printf(": ");
  cin >> s;
	if (isnumber(s) == 1){
		if(d == 5){return 0;}
		else if(d<5){int value = atof(s.c_str()); 
			if(gt1na(value) == 0){
				return value;}
			else if(gt1na(value) == 1){
				cout<<"\n That's incorrect. \n"; 
				n=d+1;
				d=n;
				goto redo;}
			}
		else {n=d+1; d=n; goto redo;}
		}
	else if(isnumber(s) == 1){goto redo;}
}




Was This Post Helpful? 0
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,124
  • Joined: 05-May 12

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 29 November 2013 - 08:13 PM

View Postsporte00, on 29 November 2013 - 04:22 PM, said:

The problem is the same as before. The printf that displays the menu is still malfunctioning. Also I have the rest of the program working. So i guess I only need help fixing that.


Since your code is so poorly written with bad names for functions, I can only take what you say literally... So your code that displays the menu is:
void PrintMenu_and_MenuInstructions( void){ 
		printf("%s",
		"________________________________________________________________________________"
		"==============================Meal Planner 10K=================================="
		"-Directions: \n"
		"    1.)Specify the most money you're willing to spend.                          "
		"    2.)Specify the maximum amount of calories you're willing to consume.        "
		"-Please note: \n"
		"    a.)The total combination of the priciest items is $6.79.                    "
		"    b.)Our menu is low calorie, but cators to your cal. limits.                 "
		"    c.)If you need assistance find some.                                        "
		"================================================================================"
		"________________________________________________________________________________" 
		);
}



And that bit of code seems to work correctly...
Attached Image
Was This Post Helpful? 0
  • +
  • -

#10 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,124
  • Joined: 05-May 12

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 29 November 2013 - 08:20 PM

Now, if i were to try guess that what you meant by "menu" was the structure filedata, then that would lead me to your function wrt1(). That code is printing out the data that you read in from the file incorrectly because you are using the incorrect format specifiers in your call to [ilprintf()[/il]. The reason why your code in your "restaurants.txt" in your original post seemed to display correctly is because you were not using printf(), but instead using the C++ output streams to let the compiler determine the correct types to use.
Was This Post Helpful? 0
  • +
  • -

#11 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3576
  • View blog
  • Posts: 11,124
  • Joined: 05-May 12

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 29 November 2013 - 08:28 PM

I highly, highly, highly recommend taking time to step back and take time to clean up your code, and apply good programming practices. Use reasonable names and descriptive names for your functions, types, variables, etc. Pick an indent style and apply it consistently.

And get rid off all those goto's. You have no real need for them for what you are trying to do. A do-while loop will cover most of your needs. In psuedo code:
do
{
    get input
    if input is invalid
    {
        go insult the user
        valid = false
    }
    else
    {
        valid = true;
    }
} while (!valid);


or
do
{
    playGame();
    
    cout << "Do you want to play again?" << endl;
    cin >> response;
} while (beginsWith(response, 'Y'))


Was This Post Helpful? 0
  • +
  • -

#12 sporte00  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 26-November 13

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 30 November 2013 - 12:29 AM

That makes quite a bit of sense that it would be because of the difference between calling in c or c++. In either case i did impliment the while loops, and changed a few names. Yet what gets me now is that i cannot get it to print fruit of any kind.


// ECE 264 Advanced C Programming 
// Fall 2013 
// Samuel Porter
// Instructor: Dr.George Stefanek 
// 
// Homework 6 // Problem 9.9

#include "General_MoreHead.h"
#define twenty1 20
#define countmax 4000
#define two1  2
#define five1 5
using namespace std;
  
ifstream infile;

struct filedata{

	  int    calories;                                                   
      double cost;
	  int    id; 
	  char   *name;
	  int    OnOff;
}; 
void CreateDataFile(void);
void PrintInstructions(void);
void User_Inputs(int Intake1[]);  
void WritePredictedMeals(filedata List_Of_Foods[]);
int squencingData(void);
int FoodPicker(filedata arr[], double arr1[], double intake[], int /*Range[]*/ Numberline , int mealnumber, int count, int done[]);

void CreateDataFile(void){ 
		//create a text file in the project directory, and write to it. 
		string name = "25 .69\n5 .20\n6 .42\n7 .40\n50 .50\n85 1.75\n77 1.1\n59 .92\n62 .82\n225 .50\n147 1.9\n390 2.1\n306 .85\n500 0\n350 .12\n390 1\n140 .55\n216 .75\n163 1.25\n154 2.25";
		ofstream myfile; 
		myfile.open ("data.txt");
		myfile << name ; 
		myfile.close();
};
void PrintInstructions( void){ 
		printf("%s",
		"________________________________________________________________________________"
		"==============================Meal Planner 10K=================================="
		"-Directions: \n"
		"    1.)Specify the most money you're willing to spend.                          "
		"    2.)Specify the maximum amount of calories you're willing to consume.        "
		"-Please note: \n"
		"    a.)The total combination of the priciest items is $6.79.                    "
		"    b.)Our menu is low calorie, but cators to your cal. limits.                 "
		"    c.)If you need assistance find some.                                        "
		"================================================================================"
		"________________________________________________________________________________" 
		);
}
void PrintFoodChoicesAvalible(filedata List_Of_Foods[]){
		for(int i = 0; i < twenty1; i++)	{	
			 cout<<"[" << List_Of_Foods[i].id <<"] " << List_Of_Foods[i].name  << "|| Costs:"<< List_Of_Foods[i].cost  << "|| Calories:"<< List_Of_Foods[i].calories  <<"\n";}
}						
void User_Inputs(double Intake1[]){	

	int k,c,d;
	bool valid;
	double b,kid; 

//get the amount of money the user is going to spend with error check
	do{								
		printf("\n%s"," How much money do you wish spend");
		b=isdbl();
			if (b > 1.25){ 
				Intake1[0] = b;
				printf("...  Remember any amount of money paid over the max of $6.79 is kept as tip.\n");
				valid = true;}
			else if(b < 1.25){
				printf("\n...  You are now starving...  That is too small of a number.\n");
				valid = false;}
		}
	while (!valid);

	printf("%s","________________________________________________________________________________");


//get the amount of calories the user is going to spend with error check
	do{	 
		printf("\n%s"," How many callories do you wish to consume" );
		c =isdbl();
		if (c > 2000){
			printf("\n...  You are now fat...  That is too great of a number.");
			Intake1[0] = c;
			valid = false;}
		else if(c < 351){
			printf("\n...  You are now starving...  That is too small of a number.");
			valid = false;}
		else{valid = true;}
		}
	while (!valid);

	printf("%s","________________________________________________________________________________");
} 
int FoodPicker(filedata arr[],double arr1[], double intake[], int /*Range[]*/ Numberline , int mealnumber, int count, int done[]){
	 
	if(/*Range[5]*/ Numberline == 4){
		printf("Range fail");
		int v1 =isint();		
		 /*Range[5]=0; Range[0]=0;*/Numberline=0; count =0; return 0;} 
	else { 
			if(count == countmax ){  
				printf("countmax fail");
				int v1 =isint();
				return (FoodPicker(arr, arr1, intake, /*Range*/ Numberline, mealnumber, count, done));}
			else {
				int  RandomNumber;
				++count;
				if(/*Range[0]==0*/ Numberline==0){ 

					
					RandomNumber= rand()% 4 ; }
				else if(/*Range[1]*/ Numberline==1){ RandomNumber= rand()% 9 +5 ; }
				else if( /*Range[2]*/ Numberline==2){ RandomNumber= rand()% 14 +10 ; }
				else if(/* Range[3]*/ Numberline==3){ RandomNumber= rand()% 19 +15 ; } 
				
					if(arr[RandomNumber].OnOff==0){
						printf("RandomNumber fail");
						int v1 =isint();
						return (FoodPicker(arr, arr1, intake, /*Range*/ Numberline, mealnumber, count, done));}
					else {// get measures
						int totalCaloriesAvalible,ItemInQuestionCal,TempTotalCal;
						double CashInHand,ItemInQuestionCost,TempTotalCost;
						totalCaloriesAvalible  = intake[0];
						CashInHand = intake[1];
						ItemInQuestionCal = arr[RandomNumber].calories;
						ItemInQuestionCost = arr[RandomNumber].cost;
						TempTotalCal = arr1[mealnumber] +ItemInQuestionCal;
						TempTotalCost = arr1[mealnumber]  +ItemInQuestionCost;

						//check if the item is out of range
						if(gt0na(CashInHand-TempTotalCost) <= 0 ){							//out of range call yourself again
									return(FoodPicker(arr, arr1, intake,  /*Range*/ Numberline, mealnumber, count, done));}
						else if(gt0na(totalCaloriesAvalible-TempTotalCal) <= 0){			//out of range call yourself again
									return(FoodPicker(arr, arr1, intake,  /*Range*/ Numberline, mealnumber, count, done));}
						else {														 // use the randomly generated picked item
								if(/*Range[0]==0*/ Numberline==0){				// VEGGIE STAGE
									arr1[mealnumber]  = TempTotalCost;
									done[mealnumber]  = TempTotalCal;
									cout << "\nMeal set " << mealnumber << " \n[" <<  mealnumber << "] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n";
									arr[RandomNumber].OnOff==0; 
									/*Range[0] = 1;
									Range[1] = 0;*/
									int OleNumberline=Numberline+1;
									return(FoodPicker(arr, arr1, intake,  /*Range*/ OleNumberline, mealnumber, count, done));}
								else if( /*Range[1]*/ Numberline==1){		// FRUIT STAGE
									arr1[mealnumber] = TempTotalCost;
									done[mealnumber] = TempTotalCal;
									cout<<"[" << mealnumber+1 <<"] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n";
									arr[RandomNumber].OnOff==0; 
									/*Range[1] = 1;
									Range[2] = 0;*/
									int OleNumberline=Numberline+1;
									return(FoodPicker(arr, arr1, intake,  /*Range*/ OleNumberline, mealnumber, count, done));}
								else if( /*Range[2]*/ Numberline==2){ 
									arr1[mealnumber] = TempTotalCost;
									done[mealnumber] = TempTotalCal;
									cout <<"["<< mealnumber+2 <<"] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n";
									arr[RandomNumber].OnOff==0; 
									/*Range[2] = 1;
									Range[3] = 0;*/
									int OleNumberline=Numberline+1;
									return(FoodPicker(arr, arr1, intake,  /*Range*/ OleNumberline, mealnumber, count, done));}
								else if( /* Range[3]*/ Numberline==3){ 
									arr1[mealnumber] = TempTotalCost;
									done[mealnumber] = TempTotalCal;
									cout << "["<< mealnumber+2 <<"] " << arr[RandomNumber].name  << "|| Costs:"<< arr[RandomNumber].cost  << "|| Calories:"<< arr[RandomNumber].calories  <<"\n" 
										 << "     ||Total Cost: $ " <<TempTotalCost<<" || Total Calories" <<TempTotalCal <<" Cal.  \n" ;
									arr[RandomNumber].OnOff==0; 
									/*Range[3] = 1;
									Range[1] = 0;
									Range[5] = 1;*/
									int OleNumberline=Numberline+1;
									return(FoodPicker(arr, arr1, intake,  /*Range*/ OleNumberline, mealnumber, count, done));}}}
					
				}
		 } 
	/*delete [] Range;*/
	return 0;
}
int squencingData(void){

	struct filedata master[twenty1];
	infile.open ("Data.txt");
	char	*names[twenty1]=	 {"Carrots           ","Lettuce           ","Celery            ","Spinach           ","Broccoli          ","Blueberries       ","Cherrie           ","Peaches           ","Grapes            ","Pineapple         ","Pork             ","Beef             ","Chicken          ","A Vegan          ","Soylent          ", "Pasta            ","Whole Grain Bread","Brown Rice       ","Potato           ","Beer             "};
	double  UserIntakeValues[two1]={.01,.001}, MealPlanRecordedCosts[twenty1];
	int		Count=0;
	int		Mealnumber=0;
	int		MealPlanRecordedCalories[twenty1];
	//int		FoodTypeCounter[five1]={0,1,1,1,1};    //This was tested when i thought an array of bool using 0 and 1 for true and false might help
	int		FoodTypeCounter=0;	
 
	if (infile.fail()){
		cerr << "Can't open file for input.\n";
		int d=isint();
		exit(1);}

	for(int d = 0; d < twenty1; d++){ 
		infile		  >> master[d].calories;
		infile		  >> master[d].cost;
		master[d].name  =  names[d];
		master[d].id = d;	 
		master[d].OnOff = 1;
		MealPlanRecordedCalories[d] =d;
		MealPlanRecordedCosts[d] = (double)d;}
	

	PrintFoodChoicesAvalible(master);
	PrintInstructions();								//instructions
	User_Inputs(UserIntakeValues);						//get user data and place into an array: Intake[0]=maximum calories the user specifies
														//											     Intake[1]=maximum cash the user wishes to spend
	do{
	FoodPicker(master,MealPlanRecordedCosts, UserIntakeValues, FoodTypeCounter, Mealnumber, Count, MealPlanRecordedCalories);
	++Mealnumber;}
	while(Mealnumber!=3);
	infile.close();
/*	delete [] numberline;*/
 return 0;
} 
int  main(void){
    int r;  

	do{
	CreateDataFile();
	squencingData();
    cout <<"\n\n Again? \n Yes = 1 and No = 0: ";
    cin >> r;
    cout <<"\n"; 
	}while(r!=0);

    return 0;
};



Was This Post Helpful? 0
  • +
  • -

#13 jimblumberg  Icon User is offline

  • member icon


Reputation: 4074
  • View blog
  • Posts: 12,568
  • Joined: 25-December 09

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 30 November 2013 - 07:20 AM

Why are you mixing C++ streams and C-stdio functions? Decide whether your going to write a C++ or C program and then stick with that method. If your going to write C++ stick with the C++ streams, and get rid of the C-stdio functions like printf(). Also using void in your function definitions for functions with no parameters is a good practice in C, in C++ it is usually considered a bad practice. C and C++ differ in how they handle a function that is prototyped with no parameters.

Also don't forget that the default open mode of an ofstream deletes the contents of the file when opening.

Also for me to really offer much help you need to work on your indentation style. The way your program is currently formatted it is too hard to read and trying to follow your logic is almost impossible. Without a complete compilable program that I can run I can't be bothered to try delve too deeply.

Also my compiler is complaining about all those extra semicolons that you are using to terminate your functions. Semicolons are not required after the closing brace of a function.

Jim
Was This Post Helpful? 0
  • +
  • -

#14 #define  Icon User is offline

  • Duke of Err
  • member icon

Reputation: 1345
  • View blog
  • Posts: 4,635
  • Joined: 19-February 09

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 01 December 2013 - 12:55 AM

Hi, you can choose to use, either a C string or a C++ string in the struct.

If you print the name last, on the line, in the text file, you can use getline and read including the spaces. There are two getline functions one for a C string and a global one for a C++ string.

// Using a C string

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

#define MAXNAMESIZE     40
#define MAXNUMFOODITEMS 20

struct FoodItem
{
  int    id;
  char   name[MAXNAMESIZE];
  int    calories;
  double cost;
  bool   on;
};


//create a text file in the project directory, and write to it.
void createDataFile(char *filename)
{
  FoodItem items[MAXNUMFOODITEMS] = {
    { 101, "Carrots", 25, 0.69, 1 },
    { 102, "Pork", 390, 2.1, false },
    { 103, "Brown Rice", 216, .75, true }
  };

  int count_items = 3;

  ofstream outfile;
  outfile.open (filename);

  // print name last to ease reading
  for(int i=0; i<count_items; i++)
  {
    outfile << items[i].calories << " "
            << items[i].cost << " "
            << items[i].name << endl;
  }

  outfile.close();
}


int main()
{

  createDataFile("fooditems.txt");

  return 0;
}




Using a C++ string

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

#define MAXNAMESIZE     40
#define MAXNUMFOODITEMS 20


// use C++ string
struct FoodItem
{
  int    id;
  string name;
  int    calories;
  double cost;
  bool   on;

  FoodItem() {}
  FoodItem(int i, const string &n, int cals, double c, bool o)
    : id(i), name(n), calories(cals), cost(c), on(o) {}
};



//create a text file in the project directory, and write to it.
void createDataFile(char *filename)
{
  FoodItem items[MAXNUMFOODITEMS] = {
    { FoodItem(101, "Carrots", 25, 0.69, 1) },
    { FoodItem(102, "Pork", 390, 2.1, false) },
    { FoodItem(103, "Brown Rice", 216, .75, true) }
  };

  int count_items = 3;

  ofstream outfile;
  outfile.open (filename);

  // print name last to ease reading
  for(int i=0; i<count_items; i++)
  {
    outfile << items[i].calories << " "
            << items[i].cost << " "
            << items[i].name << endl;
  }

  outfile.close();
}


int main()
{

  createDataFile("fooditems.txt");

  return 0;
}


Was This Post Helpful? 0
  • +
  • -

#15 sporte00  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 26-November 13

Re: Sorting/Swaping/File(i/o)_withStrings Struct Arrays

Posted 02 December 2013 - 02:50 AM

I'm going to put an update to the code from the newest suggestions sometime late tomorrow, because I'm working on another project that's has to be done sooner that this code.

--#Define--
I haven't seen an example of filling a struct like that before, and I'm going to implement some of the i/o file implementation you demonstrated. Also thanks for the direct c vs c++ example I'm going to try to focus a mostly c code from now on
struct FoodItem
{
  int    id;
  string name;
  int    calories;
  double cost;
  bool   on;

  FoodItem() {}
  FoodItem(int i, const string &n, int cals, double c, bool o)
    : id(i), name(n), calories(cals), cost(c), on(o) {}
};



--Jim--
I think that for some time now I have been going for a lisp styled format, but if it helps those that review my code more then I'll gladly switch to allman. Also you are correct in pointing the vast number of overlays between types of code. I have for sometime not been sticking to one or the other. I'm going to make the switch tomorrow(uber late) hopefully.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2