ch2-GetWords (Break file into words)
Chapter_2 Exercise_2-2 Fillvector | Exercise_2-3 |
GetWords.cpp TCP1, p. 117 download
// Break a file into whitespace-separated words
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ifstream;
int main()
{
vector<string> words;
ifstream in("GetWords.cpp");
string word;
while(in >> word)
{words.push_back(word);}
int size = words.size();
for(int i = 0; i < size; i++)
{cout << words[i] << endl;} // one word per line
}
/*
g++ GetWords.cpp -o GetWords
./GetWords
*/
Note:
We can also iterate the vector with the for-each_syntax:
for (string word : words) // for all strings in vector<string> words
{cout << word << endl;} // one word per line
In this case, we no longer need the size variable:
int size = words.size();
Chapter_2 Exercise_2-2 Fillvector | BACK_TO_TOP | Exercise_2-3 |
Comments
Post a Comment