Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

#include using std::cout, std::cin, std::cerr, std:: endl; #include using std::string; #include using std::istringstream, std::istream, std::ifstream; void printError ( const char * fileName ) { cerr

#include
using std::cout, std::cin, std::cerr, std:: endl;
#include
using std::string;
#include
using std::istringstream, std::istream, std::ifstream;
void printError(const char* fileName){
cerr << "ERROR: can't open" << fileName << endl;
}
//istream general input
void head (istream& input, int numLines){
string line;
int linesRead =0;
while (linesRead < numLines && getline(input, line)){
linesRead++;
cout << line << endl;
}
}
int main (int argc, char* argv[]){
int numLines =10;
//if no arguments provided, read 10 lines
if (argc ==1){
head(cin, numLines);
}
else if (argc ==2){
//if two arguments are provided, read the specified number of lines
//check it's a number or a filename
ifstream file(argv[1]);
if (file.is_open()){
head(file, numLines);
}
else {
printError(argv[1]);
return 1;
}
}
ifstream file(argv[1]);
if (file.is_open()){
head(file, numLines);
}
else {
//file that does not exist example
printError(argv[0]);
return 1;
}
return 0;
}
how would i modify my code to meet these requirements?
Write a head program in head.cpp
.
The head program should read the first n lines of either a file or standard input
If n isn't provided, print
1
0
lines
If no file is provided, read the lines from standard input
(
cin
)
There are four possible scenarios for command
-
line arguments:
No arguments: the program should read
1
0
lines from standard input.
1
argument that is an input file: the program should attempt to read
1
0
lines from the file.
1
argument that is a number of lines n: the program should read that number of lines from standard input.
-
NOTE: Empty lines
(
"
"
)
count as valid input. The program should accept them the same way it accepts non
-
empty lines.
2
arguments: the program should read n lines from the file.
If the input file does not exist, the program should print an error message and exit
If more lines are requested than the input file has, the program should just print as many lines as the file has and no extras.
Follow the formatting demonstrated in the example

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Securing SQL Server Protecting Your Database From Attackers

Authors: Denny Cherry

3rd Edition

0128012757, 978-0128012758

More Books

Students also viewed these Databases questions