Exercise 2-7 (less - Display a file a line at a time)

Chapter_2     Exercise_2-6 Intvector     Exercise_2-8







Exercise 2-7     TCP1, p. 120


Exercise 2-7. Display a file a line at a time, waiting for the user to press the "Enter" key after each line.




DisplayFile.cpp         download


// Displays the file one line at a time. Press Enter to continue.
// Press Enter after each line is displayed.
#include <cstdio> // for getchar()
#include <string>
#include <iostream>
#include <fstream>
using std::cout;
using std::cin;
using std::string;
using std::ifstream;

int main()
{
char c;
ifstream in("DisplayFile.cpp");
string line;

while(getline(in, line))
{
cout << line; // no newline here
cin.ignore(); // getchar(); // Press Enter to continue
}
}
/*
g++ DisplayFile.cpp -o DisplayFile
./DisplayFile
*/





Notes:

There are two ways (presented here) to wait for the user to hit a key before continuing (similar to the UNIX_less command). One is cin.ignore(); and the other one is getchar();
You should only hit ENTER (not other key) for the file display to work as intended. Each line is displayed without newline at the end, whose place it taken by hitting ENTER. User input/output is normally buffered and the buffer is cleared after hitting ENTER (or printing newline). As such, if you hit the space bar two times and then ENTER, three lines will then be displayed (with no newlines ending the first two of them).









Chapter_2     Exercise_2-6 BACK_TO_TOP Intvector     Exercise_2-8



Comments

Popular posts from this blog

Contents