ch2-Fillvector (Read file into a vector of strings)

Chapter_2     Exercise_2-2     FillString GetWords     Exercise_2-3







Fillvector.cpp     TCP1, p. 115-116         download


// Copy an entire file into a vector of string
#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("Fillvector.cpp");
string line;

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

int size = v.size();
// Add line numbers:
for(int i = 0; i < size; i++)
{cout << i+1 << ": " << v[i] << endl;} // first line is line 1, not 0
}
/*
g++ Fillvector.cpp -o Fillvector
./Fillvector
*/





Notes:

v.push_back(line); adds each new line after the last read one, keeping the lines in the same order as in the original file. We print the line numbers starting at 1, so we write  cout << i+1  instead of  cout << i. The function call v.size() is expensive inside a loop, so we store the size of v in an int variable and then refer to this variable inside the loop:
int size = v.size();
for(int i = 0; i < size; i++)









Chapter_2     Exercise_2-2     FillString BACK_TO_TOP GetWords     Exercise_2-3



Comments

Popular posts from this blog

Contents