Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

C++ File Handeling Problem

+4 votes
asked Jun 28, 2023 by Eidnoxon (5,140 points)

I have just started learning file handeling in C++.

I know the basics, like fstream contains ofstream | ifstream, etc.

I tried to make a project, but there I needed a function that prints out all the numbers from a txt file.
You might thing that this code would work:

int gpr(const string& filename){
         fstream file
         file.open(filename, ios::in);

         if(!file){
                  cout << "The program is unable to locate the file." << endl;
                  return -1;
         }

         int value;
         file >> value;
         file.close();
         return value;
}

Which would, but the only problem is that it only reads the first line. Like if my txt file contains this:
90
102
91

The overall results would be 90. The other ones under 90 are getting ignored. I need a code that reads every single line and returns an integer. Please, make sure your code is:
1. Simple
2. Understandable
3. Not so long(in columns)
4. only contains these libraries: iostream, fstream, string. Nothing else.

1 Answer

0 votes
answered Jun 30, 2023 by Peter Minarik (86,110 points)

You need to iterate through the whole file, not just read once from it. Collect the numbers in your preferred collection (std::vector<int> would be my number 1 choice probably) and return that, like this:

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

std::vector<int> gpr(const std::string & fileName)
{
    std::ifstream file(fileName);
    std::vector<int> values;

    if (!file)
    {
        std::cout << "The program is unable to locate the file." << std::endl;
        return values;
    }
    
    while (!file.eof())
    {
        int value;
        file >> value;
        values.push_back(value);
    }
    
    file.close();
    return values;
}

int main()
{
    std::vector<int> values = gpr("numbers.txt");
    for (int value : values)
        std::cout << value << std::endl;

    return 0;
}
commented Jul 4, 2023 by Md Momin (110 points)
Im in my work
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...