0

I am trying to read a text-file based using the >> stream operator, but this seems to read the file word by word:

void printFile(char filename[])
{
    ifstream input;
    input.open(filename);

    char output[50];
    if (input.is_open()) {
        while (!input.eof()) {
            input >> output;
            cout << output << endl;
        }
    }
    else cout << "File is not open!";

    input.close();
    cout << endl;
}

The only problem with this is that it won't print out the linebreaks.

Please note that I'm still learning C++ and the goal is to achieve this without using strings (so without getline). Is there any way of doing this, or is it simply impossible?

Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97
  • 1
    Is the goal just to not getline? You could read in by character instead which would prevent losing '\n' – odin Feb 06 '17 at 21:30
  • Read the file using getline(), that way you don't need to worry about line breaks. And read https://latedev.wordpress.com/2012/12/04/all-about-eof to see why not to loop on eof(). –  Feb 06 '17 at 21:31
  • @NeilButterworth I think you missed a part of my question – Duncan Lukkenaer Feb 06 '17 at 21:33
  • @odin Thanks, that worked! – Duncan Lukkenaer Feb 06 '17 at 21:34
  • http://stackoverflow.com/questions/1911822/using-istream-iterator-and-reading-from-standard-input-or-file – Steephen Feb 06 '17 at 21:35
  • @NeilButterworth About the goal being not using strings and getline – Duncan Lukkenaer Feb 06 '17 at 21:36
  • Why would you avoid using them, but use iostreams, which are far more complex? Wherever you are learning C++, it's a bad place. –  Feb 06 '17 at 21:39
  • 1
    Don't use `.eof()` use: `while (input >> output)` – Raindrop7 Feb 06 '17 at 21:42
  • @NeilButterworth We're challenged to solve this with just chars. Of course we also learn to use strings in other scenario's. It's basically just learning to think out of the box – Duncan Lukkenaer Feb 06 '17 at 21:49
  • Thinking out of the box would be implementing this with `double`s. What you are doing is learning 1970's style C. Good from a historical point of view, but not so useful if your long-term goals include employment. Not much work at the moment for historical computing, but 2038 is rapidly approaching and 2000 was a real shot in the arm for COBOL experts. – user4581301 Feb 06 '17 at 22:07

2 Answers2

1

Thanks to @odin I found the solution by reading the file by character instead of by word:

void printFile(char filename[])
{
    char ch;
    fstream fin(filename, fstream::in);
    while (fin >> noskipws >> ch) {
        cout << ch;
    }
    fin.close();
}
Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97
1

You can identify an end of a line as follow

int main(){

    char ch;
    fstream fin("filename.txt", fstream::in);
    while(fin >> noskipws >> ch){
        if(ch == '\n') {   // detects the end of the line
            cout << "This is end of the line" << endl;
        }
    }
    return 0;
}