read from a txt file

I wrote this simple piece of code

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

using namespace std;
int main(int argc, const char * argv[]) {
    
    fstream file("~/txt.txt");
    if (file.is_open())
    {
        cout << "File not open" << endl;
        return -1;
    }
    for (string line; getline(file,line); ) {
        cout << line << endl;
    }
    cout << "done" <<endl;
    return 0;
}


Which purpose is to read from a file, and print each line...

the file being

jhjhjkhjkhjkhjk
jhkjhjkhkjhjk
jkbkjhkjjk
jbkjbb

But nothing, gets printed out.. i am been wondering why for ages.. I really don't get it.
~ is interpreted by the shell, so don't use in a C/C++ program.

file.is_open() should probably be !file.is_open()

Nicely written, but don't add const to main.
Last edited on
Topic archived. No new replies allowed.