Skip to content

Reading from Files with Loops

Often we don't know how much data is within a file. Therefore, we use a sentinel-controlled loop to end when we reach the end of the file (EOF).

EOF-Controlled While Loop

This is the data file from the video, data.txt
txt
43	64	28	81	71	57	52	36	72	24
76	11	86	89	50	54	63	1	15	71
42	88	33	26	99	29	37	97	73	19
26	52	49	50	53	76	49	62	26	94
1	55	29	98	1	39	6	80	37	4
10	39	10	94	49	13	44	36	28	50
1	10	84	22	78	87	76	41	15	2
54	43	94	45	8	46	24	72	22	82
20	55	80	49	73	72	33	45	16	34
27	96	41	37	33	66	79	67	82	25

Often, we want to read a file until we are at the end of a file (EOF). If you are importing from a file, there is a function called eof(), which returns true if you have reached the end of the file, and false otherwise. Alternatively, the input stream variable itself will return true if (1) you are not at end of the file and (2) you do not have an input error.

cpp
ifstream inFile; // declare the input stream variable
string word; // variable to hold input

inFile.open("test.txt"); // open the file

inFile >> word; // read first value (if there is a value to read)
while (inFile) // make sure the stream is good (no errors, not at EOF).
{
    ... // do something with word.
    inFile >> word; // update the loop control variable
}
inFile.close();// close the file

If you use eof(), make sure your input file does not have a blank line of space after the last value.