Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Oct 31, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Reading a String from a File

<fstream> classes overload the operators >> for reading from a file and << for writing to it. There are several overloaded versions for each operator, one for each built-in type. In addition, these operators support several user-defined types, including std::string. You can use these operators for reading and writing data to a file. The following function reads all the words in a text file into a string using << and stores each retrieved string in a vector:

#include <fstream>
#include <string>
using namespace std;
int main()
 ifstream ftext;
 string word;
 vector <string> vs;
 if (!ftext) 
  exit (-1);
 while (ftext>>word) // as long as sizeof hasn't been reached
  vs.push_back(word); //copy word to vector
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date