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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
Thanks for your registration, follow us on our social networks to keep up-to-date