Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream from file with <fstream>

Tags:

c++

fstream

How it's possible to read characters from file without loosing the spaces?
I have a file which contains for istance this:
The quick brown fox jumps over the lazy dog.
When I read from file (a character a time), I lose the spaces, but the all other characters are correctly read. Why?
This is an example of code:

unsigned int cap = (unsigned)strlen("The quick brown fox jumps over the lazy dog.");
char c[cap];
int i = 0;
while (!fIn.eof()) {
    fIn >> c[i];
    ++i;
}

for (int i = 0; i < cap; i++)
    cout << c[i];

When i print the array, all spaces are missing. Could you tell me how I can avoid this problem?

like image 673
Overflowh Avatar asked Nov 17 '25 06:11

Overflowh


1 Answers

You can use the stream manipulators declared in <iomanip>.

std::noskipws is the one you want, which instructs stream extraction operators not to skip whitespaces.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>

int main()
{
    std::ifstream ifs("x.txt");

    ifs >> std::noskipws;

    std::copy(std::istream_iterator<char>(ifs),
              std::istream_iterator<char>(),
              std::ostream_iterator<char>(std::cout));
}

The other option is to use raw input functions fstream::get(), fstream::read().

like image 87
jrok Avatar answered Nov 19 '25 21:11

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!