WITH
myfile >> myArray[i];
you read the file word by word, which causes missing spaces.
You can read the whole file in a line with
std::ifstream in("FileReadExample.cpp"); std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
And then you can use contents.c_str() to get a char array.
How it works
std::string has a range constructor that copies a sequence of characters in a range [first, last] notes that it will not copy the last in the same order:
template <class InputIterator> string (InputIterator first, InputIterator last);
std::istreambuf_iterator iterator introduces an iterator that reads consecutive elements from the stream buffer.
std::istreambuf_iterator<char>(in)
will create an iterator for our ifstream in (the beginning of the file), and if you do not pass any parameters to the constructor, it will create an end stream iterator (last position):
The default built std :: istreambuf_iterator is known as an end-of-stream iterator. When a valid std :: istreambuf_iterator reaches the end of the underlying stream, it becomes equal to the end of stream stream iterator. Expressing dereferencing or adding it further causes undefined behavior.
So, this will copy all the characters, starting from the first in the file, until the next character becomes the end of the stream.
source share