Question On fin.get()

Just trying to confirm if I correctly understand this function.

So based on how the code below each time fin.get() is called, the next character on the file is read. I believe this is true because I removed the c = fin.get() in the while statement and it game me an infinite loop of the first character. So basically if I didn't have a loop but wanted to read the next character, I'd have to constantly use fin.get() again and again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  
#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ifstream fin("input.txt");



    int char_count = 0;
    char c = fin.get();  // must read at least one character
                         // for fin.eof() to work
    while (!fin.eof()) { // loop until end-of-file reached
        ++char_count;

            cout << char_count << " '" << c << "'\n";

        c = fin.get();
    }
    cout << char_count << " characters\n";
}
Your understanding seems correct.
Topic archived. No new replies allowed.