1. Reading Data from Files Input data read from the keyboard and output data wri
ID: 3704625 • Letter: 1
Question
1. Reading Data from Files Input data read from the keyboard and output data written to the screen are temporary and will be lost when the program ends. In this lab component, you will learn to read from a file. The reading from/writing to a file in a program is usually referred to as file /O (Input/Output). You will use constructs called streams to read from or write data to a file. Streams are among the first examples of objects introduced in this course. An object is a special kind of variable. C++ is an Object Oriented Programming (OOP) language, i.e., it has the ability to handle objects. Before we get started writing the program, create a text file called act9A.txt that will contain the following integer values, each on a separate line as follows: 236 19 917 83 148 385 74 Working with files consists of the following four steps: a. Declare the stream variables (don't forget to includeExplanation / Answer
//File Name: Lab9A.cpp
#include<iostream>
#include<fstream> // For ifstream
#include<stdlib.h> // For exit() function
using namespace std;
// main function definition
int main()
{
// ifstream object declared to read file contents
ifstream rFile;
// To store sum of all numbers read from file
int sum = 0;
// To store the number temporarily read from file
int no;
// Opens the file for reading
rFile.open("act9A.txt");
// Check that file can be opened or not
// is_open() function returns true if a file is open and associated with this stream object.
// Otherwise returns false.
if(!rFile.is_open())
{
// Displays error message
cout<<" Error: Unable to open the file!";
exit(0);
}// End of if condition
// Loops till number of rows
while(!rFile.eof())
{
// Reads data from file and stores it in variable no
rFile>>no;
// Calculates sum
sum += no;
}// End of ouster for loop
// Close the file
rFile.close();
// Displays the sum
cout<<" Sum of all the numbers read from file: "<<sum;
}// End of main function
Sample Output:
Sum of all the numbers read from file: 1869
act9A.txt file contents
236
19
917
83
148
7
385
74
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.