0

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.

bytecode77
  • 14,163
  • 30
  • 110
  • 141
  • `while (textFile >> text) text += textFile;` What? You need to get a [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and get the basics straight. – Baum mit Augen Mar 15 '15 at 19:04
  • You are getting a compiler error, maybe? And you need help understanding what the error is telling you? – Drew Dormann Mar 15 '15 at 19:05

2 Answers2

1

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);}
Jahid
  • 21,542
  • 10
  • 90
  • 108
0
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.

slugonamission
  • 9,562
  • 1
  • 34
  • 41