How to allow user to access specific sections of a file?

Hello, I am attempting to code a program that allows the user to create what is an essence a database of monsters and their statistics. The user is supposed to be able to input the name of the monster and its statistics, and then be able to access that information by typing in the name of the monster which would bring up the stat block only for that specific monster. The user also needs to be able to access all of the monsters they've inputted even after they have closed the program and later reopened it. How do I make it so the user can access specific creatures written to the creatures file just by typing in the creature's name?

Last edited on
Can you show us your broken output?
1
2
3
4
5
6
7
8
        std::ifstream inf("creatures.dat");
        while (inf)
            {
                std::string strInput;
                getline(inf, strInput);
                cout << strInput << endl;
            }
        }


outputs everything in the file. Output conditionally.
How do I set up the conditions for the output so that it will only read the monster requested by the user?
Read in the name. If the name matches what you're looking for, output the following stats that are part of the record for that monster. If not, then extract, but do not output the following stats that are part of the record for that monster. Rinse and repeat until you've exhausted the monster records or have found the one you're looking for.
OP: you'll need to have a line counter that'll read off the line number of the file where any given monster name search yields a positive result. Then you'll have to print out this line. A stylized suggestion is below, please edit it as per your needs with error checking and other conditions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
cout<<"Enter monster name to search: \n";
string search;
getline (cin, search); 
ifstream File ("creatures.data");
if(File.is_open())
{
	string line; 
	int curLine = 0; 
	while(getline(File, line))
	{
		curLine++;
		if(line.find(search,0)!=string::npos)
		{
			break;
		}
		else
		{
			cout<<"Given monster name doesn't exist in the file! \n";
		}
		for(int line_num = 0; line_num < curLine + 1; line_num++)
		{
			if(getline(File, line) && (line_num == curLine)
			{
				cout<<line<<"\n";
			}
		}
	}
}

Thanks for the suggestion, I'll try fiddling around with it some more and see what happens
Topic archived. No new replies allowed.