user3493435 user3493435 - 2 days ago 4
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

apple,30

banana,20

pear,10




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
thanks.

Answer

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
        }
    }
}
Comments