I am trying to create a database program, which gets its data from a .txt file. My text file is a list of various things (we'll use fruits in this case), and my program is supposed to call up all the objects that start with a certain letter. My text file is as follows:
//Include the libraries required
#include <string>
#include <iostream>
#include <fstream>
//Use the standard namespace
usingnamespace std;
void main ()
{
//Declare the variables
char First_Letter;
string Fruit;
//Initialize the filestream
ifstream FruitData;
//Open the text file
FruitData.open ("Fruits.txt");
cout << "Enter the first letter of the fruit you're looking for." << endl;
//Set a marker for the goto function later
Retry:
//User inputs first letter
cin >> First_Letter;
if (First_Letter == 'A')
{
/*This is the point that I want the program to get all the fruits that begin
with A, but it only gets the first line, minus the first letter (pple).*/
FruitData.get (First_Letter);
FruitData >> Fruit;
cout << Fruit << endl;
system("PAUSE");
}
elseif (First_Letter == 'D')
{
//Here, it gets Apple again, and, just like before, takes away the first letter.
FruitData.get (First_Letter);
FruitData >> Fruit;
cout << Fruit << endl;
system("PAUSE");
}
else
{
cout << "Please try again with either A or D." << endl;
goto Retry;
}
FruitData.close ();
}
Here's the output:
Enter the first letter of the fruit you're looking for.
A
pple
Press any key to continue...
If I try again with D instead...
Enter the first letter of the fruit you're looking for.
D
pple
Press any key to continue...
You'l want to read the contents into an array or structure of some sort.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <vector>
#include <string>
std::vector<std::string*> Fruits;
std::string* fruit;
while(!FruitData.eof())
{
fruit = new fruit;
getline(FruitData, fruit, '\n');
fruits.push_back(fruit);
}
then you loop through and match the first case. if it matches, then add the string to a found list. Then output the found list.
Don't forget to delete the created memory. the STL only clears the nodes it creates and any memory it allocated. But if you create memory outside of the class, you need to free it yourself.
cin.get() and the >> extraction operator both remove the item that was found from the buffer. that's why you'll need to create some sort of list and access the data that way.
Also, don't use goto. It creates weird code that jumps randomly. If you need to use goto, consider creating a function instead.