Exercise 2-6 (Concatenate vectors into a string)

Chapter_2     Exercise_2-5 Exercise_2-7







Exercise 2-6     TCP1, p. 120


Exercise 2-6. Change Fillvector.cpp so that it concatenates all the elements in the vector into a single string before printing it out, but don’t try to add line numbering.




CatFillvector.cpp         download


// Copy an entire file into a vector of string, concatenate strings
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using std::cout;
using std::string;
using std::vector;
using std::ifstream;

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

while(getline(in, line))
{v.push_back(line);} // Add the line to the end

line = ""; // reset line
int size = v.size();
// Concatenation:
for(int i = 0; i < size; i++)
{line += v[i] + "\n";}

cout << line;
}
/*
g++ CatFillvector.cpp -o CatFillvector
./CatFillvector
*/









Chapter_2     Exercise_2-5 BACK_TO_TOP Exercise_2-7



Comments

Popular posts from this blog

Contents