Добавление int из файла txt в вектор в c ++ - PullRequest
0 голосов
/ 08 декабря 2018

Написание программы, которая читает текстовый файл, вводит значения в вектор, а затем определяет количество значений (температур), которые ниже нуля.Я продолжаю получать 0 в результате и не могу понять, что я не так.Любая помощь будет принята с благодарностью!

Ниже приведен актуальный заданный вопрос и мой код. Напишите основную программу, которая запрашивает у пользователя имя файла.Файл содержит дневные температуры (целые числа).

Основной вызывает две функции для (1) сохранения температуры в векторе (2) отображения количества дней с температурами замерзания (<= 32 ° F). </p>

 #include <iostream>
 #include <vector>
 #include <fstream>
 #include <string>

 using namespace std;

 //prototypes
 void readTemperaturesFromFile(vector<int>& V, ifstream&);
 int countFreezingTemperatures(vector<int>& V);


 int main()
{
ifstream ins;
string fileName;
int totalFreezing = 0;
vector<int> temperature;

cout << "Please enter the name of the file: ";
cin >> fileName;

ins.open(fileName.c_str());

readTemperaturesFromFile(temperature, ins);
totalFreezing = countFreezingTemperatures(temperature);

cout << "Total number of days with freezing temperature: " << totalFreezing << 
endl;



ins.close();
system("pause");
return 0;
}

// The function reads temperatures (integers) from a text file and adds 
// pushes them to the vector. The number of integers in the file is 
// unknown
void readTemperaturesFromFile(vector<int> &V, ifstream& ins)
{
int temperature, v;
while (ins >> v)
{
    V.push_back(v);
}

}

// The function returns the number of freezing temperatures (<=32oF) 
// in the vector. 
// You need to consider the case where the vector is empty
int countFreezingTemperatures(vector<int>& V)
{
int counter = 0;
if (V.empty());
cout << "empty" << endl;

for (int i = 0; i < V.size(); i++)
    if (V[i] <= 32)
    {
        return counter;
        counter++;
    }
 }

Ответы [ 2 ]

0 голосов
/ 08 декабря 2018

Ваша countFreezingTempera реализация возвращает 0. Взгляните:

for (int i = 0; i < V.size(); i++)
    if (V[i] <= 32)
    {
        return counter;
        counter++;
    }
 }

Этот код говорит: "сразу после достижения температуры в / ниже 32, счетчик возврата" (который являетсяустановить в 0).

Вот исправление:

for (int i = 0; i < V.size(); i++)
    if (V[i] <= 32)
    {
        counter++;
    }
 }
return counter;
0 голосов
/ 08 декабря 2018

Вам нужно изменить countFreezingTemperatures функцию
Там нет необходимости ; после ifВы должны посчитать всю температуру <=32oF и затем вернуть counter

int countFreezingTemperatures(vector<int>& V)
{
  int counter = 0;
  if (V.empty())
  {
     cout << "empty" << endl;
  }
  else
  {
    for (int i = 0; i < V.size(); i++)
    {
       if (V[i] <= 32)
       {  
         counter++;
       }
     }
  }
  return counter;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...