В настоящее время написан этот простой код, пытающийся выяснить, почему он не считает конкретные слова каждый раз.
#include "pch.h"
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
int t = 0;
int a1 = 0;
string a[100];
ifstream food;
food.open("food.txt");
if (food.fail())
{
cout << "File can't open" << endl;
}
else
cout << "File successfully opened" << endl;
int i = 0;
while (!food.eof())
{
// Tomato
food >> a[i];
if (a[i] == "tomato")
{
t = t + 1;
}
i++;
// Apple
food >> a[i];
if (a[i] == "apple")
{
a1 = a1 + 1;
}
i++;
}
cout << "Amount of Tomatos: " << t << endl;
cout << "Amount of Apples: " << a1 << endl;
}
Текстовый файл, который я использую:
apple
apple
tomato
apple
tomato
tomato
Вывод:
File successfully opened
Amount of Tomatoes: 2
Amount of Apples: 2
Цель состоит в том, чтобы найти количество каждой пищи, найденной в списке.В настоящее время я использую только два вида пищи, но у меня будет гораздо больше.