How to copy a .txt file to a char array in c++-Collection of common programming errors
With
myfile >> myArray[i];
you are reading file word by word which causes skipping of the spaces.
You can read entire file into the string with
std::ifstream in("FileReadExample.cpp");
std::string contents((std::istreambuf_iterator(in)),
std::istreambuf_iterator());
And then you can use contents.c_str()
to get char array.
How this works
std::string
has range constructor that copies the sequence of characters in the range [first,last) note that it will not copy last, in the same order:
template
string (InputIterator first, InputIterator last);
std::istreambuf_iterator
iterator is input iterator that read successive elements from a stream buffer.
std::istreambuf_iterator(in)
will create iterator for our ifstream in
(beginning of the file), and if you don’t pass any parameters to the constructor, it will create end-of-stream iterator (last position):
The default-constructed std::istreambuf_iterator is known as the 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 iterator. Dereferencing or incrementing it further invokes undefined behavior.
So, this will copy all characters, starting from the first in the file, until the next character is end of the stream.