C++ fstream read text file character by character

Introduction

To read from a file, one character at the time we can use file stream's >> operator:

#include <iostream> 
#include <fstream> 

int main() /*  w  w  w . java 2 s  . c  o m*/
{ 
    std::fstream fs{ "myfile.txt" }; 
    char c; 
    while (fs >> c) 
    { 
        std::cout << c; 
    } 
} 

This example reads the file contents one character at the time into our char variable.

By default, this skips the reading of white spaces.

To rectify this, we add the std::noskipws manipulator to the above example:

#include <iostream> 
#include <fstream> 

int main() //from   ww  w  . j a v  a2s  .  c  o m
{ 
    std::fstream fs{ "myfile.txt" }; 
    char c; 
    while (fs >> std::noskipws >> c) 
    { 
        std::cout << c; 
    } 
} 



PreviousNext

Related