Как читать файл с 3 столбцами без массивов и структур - PullRequest
0 голосов
/ 18 июня 2020

Я пытаюсь взять блокнот с 3 разными строками кода и разделить их, потому что первый столбец - это номер дня (например, 1, 2, 3 и т.д. c.) Второй столбец скорость ветра и третья температура в градусах Цельсия, всего 30 дней информации. Мне нужно найти среднее значение всех скоростей ветра, а также найти среднее значение всех температур в файле. На данный момент это все, что у меня есть, потому что я не уверен, go как разделить столбцы, все, что меня учили, - это то, что делать с одним столбцом информации.

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
    int num_of_lines = 0;
    int average = 0;
    int wind_speed;

    ifstream infile("weatherdata_2.txt", ios::in);

    if (!infile.is_open()) {

        cout << "Unable to read weatherdata_1.txt. File may not be present in the current directory.";
        return -1;
    }

    while (!infile.eof())
    {
        for(i = 0; i < 30; i++)

        num_of_lines++;
    }

    infile.close();

    cout << "The average of the wind speeds in the file is " << endl;
    cout << "The average of the temperatures in the file is " << endl;

    cin.ignore();
    cin.get();

    return 0;
}

Это документ под названием weatherdata_2:

1 14 25
2 12 31
3 5 35
4 11 33
5 8 21
6 9 35
7 12 25
8 13 34
9 8 32
10 13 28
11 6 32
12 13 29
13 6 28
14 8 35
15 5 25
16 6 28
17 8 34
18 8 21
19 3 31
20 15 22 * ​​1025 * 21 5 35
22 6 33
23 12 27
24 15 27
25 12 34
26 14 23
27 14 22 * ​​1032 * 28 5 21
29 7 29
30 14 22 * ​​1035 *

1 Ответ

0 голосов
/ 18 июня 2020

Поскольку вы уже знаете, сколько строк у вас в файле, вы можете сделать это:

// the 3 accumulators
int var1 = 0;
int var2 = 0;
int var3 = 0;

int tmp; // what we will use to store what we just read

// we will loop 30 times to get the 30 lines
for(i = 0; i < 30; i++)
{
     // we read the first variable
     infile >> tmp;
     var1+=tmp; // add it to the accumulator
     infile >> tmp; // second variable
     var2+=tmp; // add it to the accumulator
     infile >> tmp; // third variable
     var3+=tmp; // add it to the accumulator
}
// print the averages
// divide by 30.0 in order to get the correct floating point output
std::cout << "Average var1: " << var1/30.0 << std::endl;
std::cout << "Average var2: " << var2/30.0 << std::endl;
std::cout << "Average var3: " << var3/30.0 << std::endl;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...