0

In a hypothetical scenario, I don't know how many items are the file. What kind of a loop would I use to read the items in the file until the file ends? Code I'm currently working with is below.

#include <iostream>
#include <fstream>
using namespace std;

int main()
{    
    ifstream inputFile;
    int num;

    inputFile.open("TenNos.txt");
    cout << "Reading data from the file. \n";
    inputFile >> num;
    cout << num << endl;
    return 0;    
}
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Nick5227
  • 21
  • 1
  • 5

2 Answers2

1
while (inputFile >> num)
{
    cout << num << endl;
}

Will read and print ints from a file until it finds something that isn't an int, the file ends, the file isn't open, or the file is rendered unreadable for any number of other reasons.

Inspecting the various state flags documented here will help you determine why the reading stopped.

More in std::istream in general. And a page on operator bool explaining how and while (inputFile >> num) works.

If, after an error is detected, you want to clean up and continue, make sure you read clear() and ignore()

user4581301
  • 33,082
  • 7
  • 33
  • 54
1

you should add fstream to be able to read files then use a while loop which reads the content of the file until the end.

#include <fstream>  // for files
#include <iostream> // printing on screen by default

int main()
{
    ifstream inputFile;
    int num;

    inputFile.open("TenNos.txt");
    cout << "Reading data from the file. \n";

    while(inputFile >> num)
        cout << num << endl;

    return 0;
}
Raindrop7
  • 3,889
  • 3
  • 16
  • 27