Exercise 2-5 (Fillvector, reverse order)

Chapter_2     Exercise_2-4 Exercise_2-6







Exercise 2-5     TCP1, p. 120


Exercise 2-5. Change Fillvector.cpp so that it prints the lines (backwards) from last to first.




RevFillvector.cpp         download


// Copy an entire file into a vector of string (in reverse order of lines)
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ifstream;

int main()
{
vector<string> v;
ifstream in("RevFillvector.cpp");
string line;

while(getline(in, line))
{v.push_back(line);} // Add line to the end, preserving line order
// Add line numbers and print in reverse, from last to first line:
for(int i = v.size()-1; i >= 0; i--)
{cout << i+1 << ": " << v[i] << endl;}
}
/*
g++ RevFillvector.cpp -o RevFillvector
./RevFillvector
*/









Chapter_2     Exercise_2-4 BACK_TO_TOP Exercise_2-6



Comments

Popular posts from this blog

Contents