CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 37
  1. #16
    Join Date
    Nov 2016
    Posts
    32

    Re: Read a line in a file and store in an array C++

    Code:
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <sstream>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    string nextstring(string str, int start_index);
    int split(string str, string a[], int max_size);
    
    int main()
    {	
    	ifstream in_stream;
    	
    	string fileName;
    	cout << "Enter the file name : ";
    	cin >> fileName;
    	
    	in_stream.open(fileName.c_str());
    	
    	//error checking
    	if (in_stream.fail())
    	{
    		cout << "File could not be opened." << endl;
    		exit(1);
    	}
    	
    	string items[50];
    	double items_value[50];
    	string recipe[50];
    	string rname = recipe[0];
    	double profit = 0;
    	int j = 0;
        string lines;
        int number_of_lines = 0;
    	
    	while(getline(in_stream, lines))
        {  
            if(lines.substr(0,7) == "Recipe:")
            {			
    			int max_size = lines.length();
    			int cnt = split(lines,recipe,max_size);
    			for (int i=0; i<cnt; i++)
    			{
    				
    			}
    			for(int i = 0; i < cnt; i++)
    			{
    				if(recipe[0] == items[i])
    				{
    					profit = items_value[i];
    					cout << "Making " << items[i] << "," << "profit = " << profit << endl;
    				}
    			}
    			for(int j = 2; j < number_of_lines; j++)
    			{
    				if(recipe[j] == items[j-3])
    					{
    						cout << "Making " << items[j-3] << "," << "profit = 0" << endl;
    					}
    			}
    		}
    	
    		   	
    		if(lines.substr(0,5) == "Item:")
    			{	
    				int beginning = lines.find_first_of(' ') + 1;
    				int next_space = lines.find(" ", beginning);
    				items_value[j] = stod(lines.substr(next_space));
    				items[j] = lines.substr(beginning,lines.find_first_of(' ', beginning) - beginning);
    				cout << "Item list is: "  << items[j] << " " << items_value[j] << '\n';
    				j++;
    			}
    		++number_of_lines;
    	}
    	 
    	return 0;
    }
    
    string nextstring(string str, int start_index)
    {
    	
    	int y =0;
    	y = str.find(' ',start_index);
    	y = y-start_index;
    	str = str.substr(start_index,y);	
    	return str;
    	
    }
    
    int split(string str, string a[], int max_size)
    {
    	int i;
    	int num = 0;
    	for (i=0; i<max_size; i++)
    	{
    		
    		a[i] = nextstring(str,num);
    		num = num + a[i].length() + 1;
    		
    		if(num >= str.length())
    		{
    			i++;
    			break;
    		}
    	}
    	
    	return i;
    }
    I have written a few functions in my new code and here comes my idea.
    1) I extracted just the item names and stored them to the array items[j].
    2) I extracted just the item values and stored them to the array items_value[j].
    3) I parsed the recipe lines into a string recipe[50]. Now, my recipe string will be {recipe:, spear, = , wood, +, wood, +, metal, ;}
    Now I made a for loop:
    i) I start recipe[1], which stores the word "spear" and look through the items[j] array. If recipe[1] is by chance is found in this items[j] array, I can start calculate the profit (which I have not gotten there yet^^).
    ii) Now I have another loop to look through the recipe items. I will now start at j = 3, and see if recipe[j] is found in the items[i], which starts at i = 0. If a duplicate is found, I make 0 profit.

    Now I have a few issues:
    1) I can only print out one line of zero profit which is for wood ( I am supposed to have 0 profit for metal as well.) I think I have not effectively found of when the for loop should stop. I created a variable called number_of_lines to count the number of lines in my txt file because I want the for loop to run through every single line of my txt file.

  2. #17
    Join Date
    Dec 2016
    Posts
    16

    Re: Read a line in a file and store in an array C++

    Didn't get to try your code, but it seems you have an empty for loop? (Might not matter.)

    From my experience, and slight difficulty could be due to using too many loops? It's a bit hard to follow, and harder to find, even for experts.

    You should try to break it up into smaller loops. You're trying to do too much at once I think. Pull it off fine, but clean code is more impressive

    Some extra pointers:
    Ever used an enum? IIRC you can set index as you want... http://www.dreamincode.net/forums/to...num-to-string/ -- side by side an array works great.

    Maybe not of use, think about the smallest steps possible. I don't think your teacher would be happy if I told you, the first letter of each line is sufficient to determine its purpose. I'm also used to reading lines until "eof", though some might call that unsafe practice.

    While I strongly encourage you debug and add breakpoints, or output extra debug info in a textfile along the way... You can surely incorporate a few more functions. The inline function type is fast.

    Try that.

    PS: Got an example of a typical input file? My concern is that if the item list were in the wrong order...? I'm still confused.

  3. #18
    Join Date
    Nov 2016
    Posts
    32

    Re: Read a line in a file and store in an array C++

    File items1.txt contains:
    Item: Wood 2.5
    Item: Metal 5.5
    Item: Cat 900
    Item: Spear 50.7
    Recipe: Spear = Wood + Wood + Metal ;

    Whatever you have been doing to this post means a lot to me.
    1) I am given two files named items1.txt and items2.txt. Items2.txt basically looks like items1.txt, with a few more items and a few more recipes!. Given this fact, items and recipes will be in a fixed order.
    2) Here are some sample outputs I am expected to show:
    Example 1 (user input is underlined):
    What file to load?
    items1.txt
    Making Wood, profit=0
    Making Metal, profit=0
    Making Cat, profit=0
    Making Spear, profit=40.2
    3) I think I called my split function to split the recipe line(s).
    4) Here is a snapshot of my screen.Name:  Screen Shot 2016-12-05 at 7.09.11 PM.png
Views: 65
Size:  39.0 KB
    I think I kinda successfully printed out the items, which are included in the recipe line, make 0 profit because the assignment says that if any item is included in the recipe, you have to buy it, meaning you make 0 profit.
    5) We can take a look at the if statement related to the "item":
    Code:
    for(int j = 3; j < number_of_lines; j++)
    			{
    				if(recipe[j] == items[j-3])
    					{
    						cout << "Making " << items[j-3] << "," << "profit = 0" << endl;
    					}
    The counter j starts at 3 because I want to check in my recipe array, the position 3 contains the world "wood", so this for loop will start at recipe[j] and compares to array items[j-3], which contains all of the words "wood, metal,cat,spear" and it will starts at position 0. If recipe[j] is the same as item[j-3], then making item[j-3] profits 0. While I am typing this, I think I have a problem dealing with this for loop too lol.

    Please let me know if you need me to explain anything else for my code.

    6) Do you think It is fine to let i < number_of_lines in my for loop? My logics for this counter less than number_of_lines is that I want the items[i] runs from position 0 or line 0 and stops at line containing recipe. I am not sure this is the right way to do it. I am really sorry I am such a newbie to you. But I am really a newbie.

  4. #19
    Join Date
    Dec 2016
    Posts
    16

    Re: Read a line in a file and store in an array C++

    Ahh, can visualize this better now. Though I don't understand how buying metal and wood makes you any money on the spear ... but that's not important.

    1) ok, my exercise in perspective, is to imagine yourself at mcdonals. Each button has a price. Some combos have discounts. if someone asks, price is on the screen.
    If my recipe, to make a cat, required wood scratching posts, and I returned some burned metal... I honestly on purpose go obscure Will go back on this register analogy.

    2) Can you explain your ingredient/price storage approach? I'm thinking your approach is accurate, efficient... however, I perceive if the menu changed, can j - 3 (your call) adapt to a greater menu with changing prices?

    3) split function. you can for(int I = 0; ...) init inside and I'd prefer a return over a break. Return value. You can make a few more functions.

    4) so profit = item value - the sum of constituant item values. 1) to me surfaces

    5) this works, but now that we are looking at it. it works. but its very confusing. don't shy from comments, 2 weeks from now youll open that piece of code and be like ***?? lol always happens to me.

    6) my issue with number_of_lines is... it's too specific.

    ---

    Your questions and n00bagz are no match for my rusting trainwreck. My tme worth apology is dubious, you found the flaws.

    ---

    I used to readline until eof. Habit. Not logic. But not safest code perhaps.... Or not. Not necessary, you can read until recipe. But otherwise a nice touch, code is fragile.

    Though I'm saying, look beyond the textfile as it is. If at mcdonalds I ask extra ..... tomatoes, just as my friend asks their recipe. I'ts my bill, two recipies. Didnn't read all the code and dunno how u store and differ but... without mainimalistic comments in the least its hard to gather.


    Umm sure the less I am specific, if you catch my drift, the more potential you are to heed return value.


    Code works. K. Adaptable and robust.. mmm needs a just a lil more thought.

    If it works, cool.

    If your teacher gives ya'll extra files to test in front of the class (lol my bro has video gaming classes) -- eesh

    But B or A+

    Right?

  5. #20
    Join Date
    Nov 2016
    Posts
    32

    Re: Read a line in a file and store in an array C++

    Sure I can explain my ingredient approach.
    1) Let's look at the way I store the items' names and items' values in two arrays items[j] and items_value[j]
    Code:
    while(getline(in_stream, lines))
        {  
            if(lines.substr(0,5) == "Item:")
    			{	
    				int beginning = lines.find_first_of(' ') + 1;
    				int next_space = lines.find(" ", beginning);
    				items_value[j] = stod(lines.substr(next_space));
    				items[j] = lines.substr(beginning,lines.find_first_of(' ', beginning) - beginning);
    				j++;
    			}
    (this is just part of my whole code)
    So for every line that contains the word "item", the code will execute this if statement. In order just to get the items' name and ignore "items:" and the price for now.
    Then basing on the position of the first space, say "Item: Wood 2.5", I find the next space and extract all the values into array items_value[j].
    This is all I can think of right now how to store an array for items' name associated with an array for items values.

    2) I am given another file called items2.txt with a bigger "Item" list and a more recipe. For now, I am just trying to deal with a simple case for now.
    3) For the final profit of a recipe, I really don't know how to subtract the recipe itself to the total of ingredients on the right.
    Code:
    for(int i = 0; i < cnt; i++)
    			{
    				if((recipe[1] == items[i]))
    				{
    	
    					profit = items_value[i];
    					cout << "Making " << items[i] << "," << "profit = " << profit << endl;
    				}
    
    			}
    4) I need help but I am really learning from this class. This is my first time in my life learning C++ and I don't care for the grade. I love to learn it and I have to get scratched on myself. But I am learning.^^

  6. #21
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Read a line in a file and store in an array C++

    re 3) Above. Shouldn't the loop termination be j rather than cnt - as j is the no of elements in the array from point 1)? This gives the item cost for the recipe name. You need to save this value. You then need to do the same for each of the elements of recipe that contain a name. Look it up in the array, find the value and maintain a running total of these values. Once you have this total from the recipe items, subtract this from the previous stored value and this will give you the required profit.

    What are the contents of items2.txt - are there any changes in the format etc?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #22
    Join Date
    Nov 2016
    Posts
    32

    Re: Read a line in a file and store in an array C++

    Items2.txt

    Item: Lint 0.01
    Item: Rubber_Chicken 20
    Item: Wood 15.2
    Item: Glasses 4.2
    Item: Substitute_Teacher 90
    Item: Cat_Toy 50
    Item: Scare_Crow 120
    Item: Dog_Toy 90
    Recipe: Substitute_Teacher = Rubber_Chicken + Glasses ;
    Recipe: Cat_Toy = Lint + Lint + Lint + Lint + Lint ;
    Recipe: Scare_Crow = Wood + Lint + Lint + Glasses ;
    Recipe: Dog_Toy = Cat_Toy + Rubber_Chicken ;

  8. #23
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Read a line in a file and store in an array C++

    The question arising from this is for Dog_Toy. This refers to Cat_Toy. Which Cat_Toy does this refer? There is an Item Cat_Toy value 50 and a Recipe Cat_Toy which has a value of 49.95 - which one is used for Recipe Dog_Toy?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  9. #24
    Join Date
    Nov 2016
    Posts
    32

    Re: Read a line in a file and store in an array C++

    The cat_toy will be from the item list, not from the recipe of cat_toy ^^
    Sample output.
    "Example 2 (user input is underlined):
    What file to load?
    items2.txt
    Making Lint, profit=0
    Making Rubber_Chicken, profit=0
    Making Wood, profit=0
    Making Glasses, profit=0
    Making Substitute_Teacher, profit=65.8
    Making Cat_Toy, profit=49.95
    Making Scare_Crow, profit=100.58
    Making Dog_Toy, profit=20"
    Last edited by hughng92; December 6th, 2016 at 10:24 AM.

  10. #25
    Join Date
    Nov 2016
    Posts
    32

    Re: Read a line in a file and store in an array C++

    Quote Originally Posted by 2kaud View Post
    re 3) Above. Shouldn't the loop termination be j rather than cnt - as j is the no of elements in the array from point 1)? This gives the item cost for the recipe name. You need to save this value. You then need to do the same for each of the elements of recipe that contain a name. Look it up in the array, find the value and maintain a running total of these values. Once you have this total from the recipe items, subtract this from the previous stored value and this will give you the required profit.

    What are the contents of items2.txt - are there any changes in the format etc?
    Code:
    while(getline(in_stream, lines))
        {  
            if(lines.substr(0,5) == "Item:")
    			{	
    				int beginning = lines.find_first_of(' ') + 1;
    				int next_space = lines.find(" ", beginning);
    				items_value[j] = stod(lines.substr(next_space));
    				items[j] = lines.substr(beginning,lines.find_first_of(' ', beginning) - beginning);
    				j++;
    			}
    			
            if(lines.substr(0,7) == "Recipe:")
            {			
    			int max_size = lines.length();
    			int cnt = split(lines,recipe,max_size);
    			for(int i = 0; i < cnt; i++)
    			{
    				if((recipe[1] == items[i]))
    				{
    	
    					profit = items_value[i];
    					cout << "Making " << items[i] << "," << "profit = " << profit << endl;
    				}
    
    			}
    			cout << "Profit is:" << profit << endl;
    			double profit1 = 0;
    			for(int j = 3; j < cnt; j++)
    			{
    				for(int i = 0; i < 4; i++)
    					{
    						if((recipe[j] == items[i] || recipe[1] != items[i]) && (recipe[j] != "+")&& (recipe[j] != ";"))
    						{
    						cout << "Making " << items[i] << ", " << "profit = 0" << endl;
    						cout << "Items' Value:  " << items_value[i] << endl;					
    						profit1 += items_value[i];						
    						}
    					}
    					break;
    			}
    			cout << "Items' Value total  " << profit1 << endl;
    		}	
    	}
    	in_stream.close();
    	return 0;
    I made two separate if statements:
    the first one is to try to find out the profit of the recipe
    the second one is to assign the zero profit the any item being used to make the recipe or any item which does not have a recipe, that is why in the end, wood and metal have 0 profit since they are used to make the recipe spear. At the mean time, since cat neither has a recipe or is included in any recipe ingredient, it also has a 0 profit.

  11. #26
    Join Date
    Nov 2016
    Posts
    32

    Re: Read a line in a file and store in an array C++

    So I kinda take care of my program except a few issue. Here is my screenshot
    Name:  Screen Shot 2016-12-06 at 9.42.15 AM.png
Views: 60
Size:  43.2 KB

    Code:
    while(getline(in_stream, lines))
        {  
            if(lines.substr(0,5) == "Item:")
    			{	
    				int beginning = lines.find_first_of(' ') + 1;
    				int next_space = lines.find(" ", beginning);
    				items_value[j] = stod(lines.substr(next_space));
    				items[j] = lines.substr(beginning,lines.find_first_of(' ', beginning) - beginning);
    				j++;
    			}
    			
            if(lines.substr(0,7) == "Recipe:")
            {			
    			int max_size = lines.length();
    			int cnt = split(lines,recipe,max_size);
    			double profit1 = 0;
    			double profit2 = 0;
    			for(int j = 3; j < cnt; j++)
    			{
    				for(int i = 0; i < 4; i++)
    					{
    						if((recipe[j] == items[i]) && (recipe[j] != "+")&& (recipe[j] != ";"))
    						{
    						cout << "Making " << items[i] << ", " << "profit = 0" << endl;			
    						profit1 += items_value[i];						
    						}
    						if(recipe[1] != items[i])
    						{
    						profit2 = 0;
    						}
    					}
    			}
    			for(int i = 0; i < cnt; i++)
    			{
    				if((recipe[1] == items[i]))
    				{
    	
    					profit = items_value[i];
    					cout << "Making " << items[i] << ", " << "profit = ";
    				}
    
    			}
    			cout << profit - profit1 << endl;
    			
    
    		}	
    	}
    	in_stream.close();
    	return 0;
    Well, I am supposed to print out:
    "Example 1 (user input is underlined):
    What file to load?
    items1.txt
    Making Wood, profit=0
    Making Metal, profit=0
    Making Cat, profit=0
    Making Spear, profit=40.2"

    Instead, I had two same lines saying Making Wood, profit=0 and I don't have a line saying Making Cat, profit=0.

    For my second file items2.txt. Here is my screen shot.
    Name:  Screen Shot 2016-12-06 at 9.44.40 AM.png
Views: 61
Size:  47.8 KB
    I have a bunch of making Lint profit 0 statements@@@@
    And I don't have a line for profit of making dog_toy, which is supposed to be 20@@
    Last edited by hughng92; December 6th, 2016 at 11:01 AM.

  12. #27
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Read a line in a file and store in an array C++

    Because you are showing a profit line for each of the items used to make a recipe! Producing the required output isn't exactly straight forward - I've coded this!

    As I suggested in my post #13, IMO you should take a step back from the code and first produce a program design, then code from the design. For a requirement such as this exercise, diving straight into the code is not going to provide a good solution.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  13. #28
    Join Date
    Nov 2016
    Posts
    32

    Re: Read a line in a file and store in an array C++

    I think this is how I interpret the requirement to produce the required out put.
    There will always be a list of items with a name and price followed by some amount of recipes. If a recipe for an item is not present, the only way to make the item is to buy it directly. Make a program that reads all the items and recipes, then says how much profit can be made by making each item.
    If an item has no recipe, you would buy that item then resell it for the same price and make a profit of 0. If an item does have a recipe, you would buy the materials to make this item and subtract this cost from the price of the final product.
    There will only be zero or one recipe per item. The items will always be listed first. The names of items will always be a single word (using a _ to join names that are normally multiple words). You may assume there will be less than 50 items and each recipe will use less than 50 other items to create a final product.
    Code:
    for(int i = 0; i < a; i++)
    					{
    						if((recipe[j] == items[i]) && (recipe[j] != "+")&& (recipe[j] != ";"))
    						{
    						cout << "Making " << items[i] << ", " << "profit = 0" << endl;			
    						profit1 += items_value[i];						
    						}
    						if(recipe[1] != items[i] && (recipe[j] != items[i]))
    						{
    						cout << "Making " << items[i] << ", " << "profit = 0" << endl;	
    						}
    					}
    I meant I have to look through the array to find out the value associated with the items being used in the recipe right? Without this loop, I will be struggling, again.
    T_T

  14. #29
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Read a line in a file and store in an array C++

    If an item has no recipe, you would buy that item then resell it for the same price and make a profit of 0
    Yes. But you only know at the end of processing the file which item(s) are not recipe items!

    Without this loop, I will be struggling, again.
    As previous, you are trying to code without a program design. This very rarely works for anything other than the simplest of programs.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  15. #30
    Join Date
    Dec 2016
    Posts
    3

    Re: Read a line in a file and store in an array C++

    Hi hughng92 I have the same assignment but my school's lab computers don't support "stod" I'm not sure how to convert a string to double

Page 2 of 3 FirstFirst 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured