1

I would like to read the content from the text file by C++ , I wrote the code as below:

#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
    ifstream input("C:\\Users\\thang\\Desktop\\Thang\\output.txt");
    string str;
    while(!input.eof()) //check if it goes to the end of the file
    { 
        //getline(input,str); //
        input>>str; // get the value of str from the file 
        cout<<str<<endl;
    }
    return 0;
}

But it just show me the result with no empty row , but the output.txt file has the empty line. I have attached the screenshot the result

my file

Could you please help explain why it get the result without the empty line ? Appriciated for all assist.

thangvc91
  • 323
  • 2
  • 10
  • 1
    Not related to the main problem, your usage of `while(!input.eof())` is [wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – MikeCAT Aug 10 '21 at 15:06
  • Thank you , Could you please advise some alternative for my case ? I thought this for checking if it goes to the end of the input file in my case. – thangvc91 Aug 10 '21 at 15:21
  • Check if reading succeeded *before* trying to use what are read like `while(input>>str)` or `while(getline(input,str))`. – MikeCAT Aug 10 '21 at 15:26

2 Answers2

2

Because the operator>> to read std::string from std::ifstream skips leading whitespaces. Newline characters is one kind of whitespace characters, so they are ignored.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

Because input>>str strips away any leading whitespace.

If you just need to read the file like cat does, use rdbuf directly:

ifstream input(...);
std::cout<<input.rdbuf()<<std::endl;

If you want to iterate over the lines, including the empty ones, use std::getline

ifstream input(...);
for (std::string line; std::getline(input, line); )
{
    ...
}
Quimby
  • 17,735
  • 4
  • 35
  • 55