devxlogo

Reading a String from a File

Reading a String from a File

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 #include using namespace std;int main(){ ifstream ftext; string word; vector  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 }}
See also  How College Students Can Shape the Future of Tech Responsibility
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist