This is a very strange issue. I’m trying to print a large text file, it’s a Wikipedia entry. It happens to be the page on Velocity. So, when I tell it to print the file, it prints “In”, when it should print “In physics, velocity is etc, etc etc”.
Here’s the code I’m using to print out:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream wiki;
wiki.open("./wiki/velocity.txt");
char* wikiRead;
wiki >> wikiRead;
cout << wikiRead << endl;
wiki.close();
}
Please help.
The default delimiter for stream is space, so when the stream encounters a space, it simply stops reading, that is why it reads only one word.
If you want the stream to read all words, the you’ve to use a loop as:
This will print all the words in the file, each on a new line. Note if any of the word in the file is more than
1024character long, then this program would invoke undefined behavior, and the program might crash. In that case, you’ve to allocate a bigger chunk of memory.But why use
char*in the first place? In C++, you’ve better choice: Usestd::string.Its better now.
If you want to read line-by-line, instead of word-by-word, then use
std::getlineas:This will read a complete line, even if the line contains spaces between the words, and will print each line a newline.