Writes a function, opens a file in read mode, reads its contents into a string vector, saves each row as a separate element in the vector, and outputs it.
Idea: 1. Open the file "directory. txt" in read mode;
2. Create a String object line and use Getline () to loop through the contents of the directory. txt in.
3. In order to store each line of content in the vector object words, use the Push_back () method of the Vectro container, i.e., words.push_back (lines);
4. Use an iterator to loop through the elements of the vector word.
1#include <iostream>2#include <fstream>3#include <string>4#include <vector>5#include <sstream>6 7 using namespacestd;8 9 intMain ()Ten { OneIfstreaminch(".. \ \ directory. txt"); A if(!inch) - { -Cerr <<"Unable to open input file! "<<Endl; the return-1; - } - stringLine ; -vector<string>words; + while(Getline (inch, line)) - { + Words.push_back (line); A } at inch. Close (); -vector<string>::const_iterator it =Words.begin (); - - while(It! =words.end ()) - { -Istringstream LINE_STR (*it); in stringWord; - while(Line_str >>word) tocout << Word <<" "; +cout <<Endl; -++it; the * } $ return 0;Panax Notoginseng}
C + + I/O library exercises