Reputation: 45
I am new to C++ and I'm having trouble understanding how to import text from a file. I have a .txt file that I am inputting from and I want to put all of the text from that file into a string. To read the text file I am using the following code:
ifstream textFile("information.txt");
Which is just reading a text file name information. I made a string named text and initialized it to "". My problem is with the following code which I am trying to use to put the text from the .txt file onto the string:
while (textFile >> text)
text += textFile;
I am clearly doing something wrong, although I'm not sure what it is.
Upvotes: 0
Views: 98
Reputation: 22428
while (textFile >> text)
won't preserve spaces. If you want to keep the spaces in your string you should use other functions like textFile.get()
Example:
#include <iostream>
#include <string>
#include <fstream>
int main(){
std::ifstream textFile("information.txt");
std::string text,tmp;
while(true){
tmp=textFile.get();
if(textFile.eof()){ break;}
text+=tmp;
}
std::cout<<text;
return(0);}
Upvotes: 1
Reputation: 9642
while (textFile >> text) text += textFile;
You're trying to add the file to a string, which I assume will be a compiler error.
If you want to do it your way, you'll need two strings, e.g.
string text;
string tmp;
while(textFile >> tmp) text += tmp;
Note that this may omit spaces, so you may need to manually re-add them.
Upvotes: 0