0

Im writing this code which reads from a text file and multiply two of the entries if its sum is 2020. Here is my code:

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

using namespace std;
int main()
{
string line;
string line_2;
int counter = 0;
int counter_2 = 0;
int n_lines = 0;
int a;
int b;
ifstream expenses("\debug\input.txt");

if (expenses.fail())
    cout << "ERROR!!";
else {
while (!expenses.eof())
{
    getline(expenses, line);
        ++n_lines;
}
for (counter++; counter < n_lines;)
{
    getline(expenses, line);
        for (counter_2++; counter_2 < n_lines;)
        {
            getline(expenses, line_2);
            a = stoi(line);
            b = stoi(line_2);

            if (a + b == 2020);
            {
                cout << a * b;
            }
        }
}
}
expenses.close();
return 0;
}

The file is in that directory and the name is correct. I don't know why it always outputs ERROR!!, as if the file could not be opened.

  • 1
    do you mean to use an absolute path ??? – ΦXocę 웃 Пepeúpa ツ Dec 09 '20 at 10:44
  • not (yet) your problem, but read this: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons. Also it is unclear what you expect to get from subsequent calls to `getline(expenses, line);` after you already read the file till `eof` – 463035818_is_not_an_ai Dec 09 '20 at 10:45

0 Answers0