Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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;
 ftext.open("data.txt");
 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.

 

 

Sitemap