3

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?

3 Answers 3

4

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().

Sign up to request clarification or add additional context in comments.

1 Comment

I assume this is because the istream::operator>>() was designed to be a console input method? (similar to how arguments to a program are tokenized by spaces). As opposed to other read/getline functions available in istream that act more like a file reader?
2

Use the method "get":

ifstream in("try.in"); char c; while((c = in.get()) && in) { cout << c; } 

6 Comments

In which header get() is defined?
For this use you need both fstream and iostream.
how does (c = in.get()) actually set c equal to the next character. From what I understand putting that in the while loop just checks to see if there is another character. Can you explain that please?
This is off topic for the question. Try to read the information available online and if there still is something unclear post a separate question
istream::get() returns a char and increments to the next char; cplusplus.com/reference/istream/istream/get istream::peek() also returns a char, but does not increment; maybe you were thinking of that?
|
1

By default an istream has the skipws (skip whitespace) flag set. This skips leading whitespace when reading.

You can turn it off using std::noskipws from <iomanip>

fIn << std::noskipws; while (!fIn.eof()) { // etc. } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.