// Header files #include <iostream> #include <fstream> #include <string> using n
ID: 661581 • Letter: #
Question
// Header files
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// main function
int main()
{
const int ROWS = 5;
const int COLS = 3;
string filename = "cet124.txt";
// open the file
ifstream infile;
infile.open(filename);
if(!infile)
{
cout << filename << " file cannot be opened." << endl;
system("pause"); // for Visual Studio
exit(EXIT_FAILURE);
}
// create the two-dimensional array
int cet124f[ROWS][COLS];
int score;
// read the scores from the file
for(int i = 0; i < ROWS && !infile.eof(); i++)
{
for(int j = 0; j < COLS; j++)
{
// read a scoe
infile >> score;
/* add 5 to score and store the new value into the array */
cet124f[i][j] = score + 5;
}
}
// print the new array of scores
cout << "Array of new scores: " << endl;
for(int i = 0; i < ROWS; i++)
{
for(int j = 0; j < COLS; j++)
{
cout << cet124f[i][j] << " ";
}
cout << endl;
}
// pause the system for a while
system("pause"); // for Visual Studio
return 0;
}
Input file: cet124.txt:
90 89 81
43 72 67
93 99 91
81 88 85
77 95 53
Explanation / Answer
// Header files
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// main function
int main()
{
const int ROWS = 5;
const int COLS = 3;
string filename = "cet124.txt";
// open the file
ifstream infile;
infile.open(filename);
if(!infile)
{
cout << filename << " file cannot be opened." << endl;
system("pause"); // for Visual Studio
exit(EXIT_FAILURE);
}
// create the two-dimensional array
int cet124f[ROWS][COLS];
int score;
// read the scores from the file
for(int i = 0; i < ROWS && !infile.eof(); i++)
{
for(int j = 0; j < COLS; j++)
{
// read a scoe
infile >> score;
/* add 5 to score and store the new value into the array */
cet124f[i][j] = score + 5;
}
}
// print the new array of scores
cout << "Array of new scores: " << endl;
for(int i = 0; i < ROWS; i++)
{
for(int j = 0; j < COLS; j++)
{
cout << cet124f[i][j] << " ";
}
cout << endl;
}
// pause the system for a while
system("pause"); // for Visual Studio
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.