Подсчитать, сколько раз слово найдено в текстовом файле - PullRequest
0 голосов
/ 14 ноября 2018

В настоящее время написан этот простой код, пытающийся выяснить, почему он не считает конкретные слова каждый раз.

#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

Цель состоит в том, чтобы найти количество каждой пищи, найденной в списке.В настоящее время я использую только два вида пищи, но у меня будет гораздо больше.

1 Ответ

0 голосов
/ 14 ноября 2018

Есть несколько проблем с вашим кодом.

  • , используя eof() в цикле неправильно. Вы не можете проверить eof() перед выполнением операции чтения.

  • использование массива без проверки границ. В этом отношении вам вообще не нужен массив.

  • пропуск слов, поэтому вы не учитываете все, что ожидаете. Давайте возьмем самую первую строку, apple. Поскольку это не "tomato", вы пропускаете его и читаете следующее слово в файле, которое является "apple", поэтому вы его считаете. Но вы вообще не считали 1-й apple.

Вам нужно сделать что-то более похожее на это:

#include "pch.h"
#include <fstream>
#include <string>
#include <iostream>

using namespace std;

int main()
{
  int tomatoes = 0;
  int apples = 0;
  string s;
  ifstream food;

  food.open("food.txt");

  if (!food.is_open())
  {
    cout << "File can't open" << endl;
    return 0;
  }

  cout << "File successfully opened" << endl;

  while (food >> s)
  {
    // Tomato
    if (s == "tomato")
        ++tomatoes;

    // Apple
    else if (s == "apple")
        ++apples;
  }

  cout << "Amount of Tomatos: " << tomatoes << endl;
  cout << "Amount of Apples: " << apples << endl;

  return 0;
}

Кроме того, как @ user463035818 упоминается в комментариях, вы можете использовать std::map вместо:

#include "pch.h"
#include <fstream>
#include <string>
#include <iostream>
#include <map>

using namespace std;

int main()
{
  map<string, int> foods;
  string s;
  ifstream food;

  food.open("food.txt");

  if (!food.is_open())
  {
    cout << "File can't open" << endl;
    return 0;
  }

  cout << "File successfully opened" << endl;

  while (food >> s) {
    foods[s]++;
  }

  for (map<string, int>::iterator iter = foods.begin(); iter != foods.end(); ++iter) {
      cout << "Amount of " << iter->first << ": " << iter->second << endl;
  }

  /* or, if you are using C++11 or later...
  for (auto &item : foods) {
      cout << "Amount of " << item.first << ": " << item.second << endl;
  }
  */

  return 0;
}
...