Read the contents of a file
-
Hi All, Can anyone tell me how to read the contents (words) of a text file into a vector/ list? I may be asking a very basic question but I am just a beginner. Hope you all understand. Thanks and Regards, Anil
Try something like this:
#include <iostream> #include <fstream> #include <string> #include <vector> #include <iterator> #include <algorithm> int main() { using namespace std; // Open the file. fstream fs("C:\\Words.txt"); if (!fs) { cerr << "Failed to open file!" << endl; return 1; } // Our vector of words. vector<string> WordList; // Place all the words in the vector. typedef istream_iterator<string> StringsIT; copy(StringsIT(fs), StringsIT(), back_inserter(WordList)); // Just for testing purposes dump all the word in the vector to the console. copy(WordList.begin(), WordList.end(), ostream_iterator<string>(cout, "\n")); return 0; }
Steve
-
Try something like this:
#include <iostream> #include <fstream> #include <string> #include <vector> #include <iterator> #include <algorithm> int main() { using namespace std; // Open the file. fstream fs("C:\\Words.txt"); if (!fs) { cerr << "Failed to open file!" << endl; return 1; } // Our vector of words. vector<string> WordList; // Place all the words in the vector. typedef istream_iterator<string> StringsIT; copy(StringsIT(fs), StringsIT(), back_inserter(WordList)); // Just for testing purposes dump all the word in the vector to the console. copy(WordList.begin(), WordList.end(), ostream_iterator<string>(cout, "\n")); return 0; }
Steve
-
Try something like this:
#include <iostream> #include <fstream> #include <string> #include <vector> #include <iterator> #include <algorithm> int main() { using namespace std; // Open the file. fstream fs("C:\\Words.txt"); if (!fs) { cerr << "Failed to open file!" << endl; return 1; } // Our vector of words. vector<string> WordList; // Place all the words in the vector. typedef istream_iterator<string> StringsIT; copy(StringsIT(fs), StringsIT(), back_inserter(WordList)); // Just for testing purposes dump all the word in the vector to the console. copy(WordList.begin(), WordList.end(), ostream_iterator<string>(cout, "\n")); return 0; }
Steve
-
If it's really an assignment the teacher will know straight away: some who can't program in C++ properly using back inserters, stream iterators and algorithms is a dead giveaway. If your assumption is incorrect then I've helped someone out.
Steve