user3493435 user3493435 - 1 year ago 112
C++ Question

C++. how to read from file and match with input

I am trying to read a textfile and matching the fruit to what I have type(e.g I type apple and it will search the textfile for the word apple and match it and output that it's been found) but I am struggling to achieve the results I wanted and thus need help in it.

I have a text file (fruit.txt) with contents shown below




this is my code

string fruit;
string amount;
string line = " ";
ifstream readFile("fruit.txt");
fstream fin;

cout << "Enter A fruit: ";
cin >> fruit;

fin >> fruit >> amount;
while (getline(readFile, line,','))
if(fruit != line) {
cout <<"the fruit that you type is not found.";

else {
cout <<"fruit found! "<< fruit;

please advise

Answer Source

In the loop with getline you read "apple" into line the first loop, and "30\nbanana" into line the second time, etc.

Instead read the whole line (using getline), and then use e.g. std::istringstream to extract the fruit and amount.

Something like:

std::string line;
while (std:::getline(readFile, line))
    std::istringstream iss(line);

    std::string fruit;
    if (std::getline(iss, fruit, ','))
        // Have a fruit, get amount
        int amount;
        if (iss >> amount)
            // Have both fruit and amount
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download