thangvc91
thangvc91

Reputation: 333

C++ - work with file (read file) then show in the console

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.

Upvotes: 1

Views: 1334

Answers (2)

Quimby
Quimby

Reputation: 19113

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); )
{
    ...
}

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

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.

Upvotes: 2

Related Questions