I am supposed to write a program that displays the first 10 lines of a file. I h
ID: 3548516 • Letter: I
Question
I am supposed to write a program that displays the first 10 lines of a file. I have a file named "characters.txt" in the same folder that my .cpp is saved in, but when I try to compile the program, it says the file cannot be found. Here is my code:
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
ifstream file; // in file an ifstream object
char word[250];
file.open("characters.txt");
if (!file.is_open())
{
exit(EXIT_FAILURE);
}
int counter = 0;
while (counter < 10 && file.good() ) // while input good and not at eof
{
file.getline(word, 250);
counter++;
cout << word << endl;
}
if (counter < 10) // if fewer than 10 lines
{
cout << " The entire file was read. ";
}
cout << "We read " << counter << " lines today. ";
cout << "Press enter to exit. ";
cin.get(word, 250);
return 0;
}
Explanation / Answer
#include <iostream> // std::cout
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
// in file an ifstream object
char word[250];
std::ifstream file ("characters.txt", std::ifstream::in);
if (!file.is_open())
{
exit(EXIT_FAILURE);
}
int counter = 0;
while (counter < 10 && file.good() ) // while input good and not at eof
{
file.getline(word, 250);
counter++;
cout << word ;
}
if (counter < 10) // if fewer than 10 lines
{
cout << " The entire file was read. ";
}
cout << "We read " << counter << " lines today. ";
cout << "Press enter to exit. ";
cin.get(word, 250);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.