I am stuck on the following question:
8. Write a program that opens a text file, reads it character-by-character to the end of
the file, and reports the number of characters in the file.
9.Do Programming Exercise 6 but modify it to get information from a file.The first
item in the file should be the number of contributors, and the rest of the file should
consist of pairs of lines, with the first line of each pair being a contributor’s name
and the second line being a contribution.That is, the file should look like this:
4
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Rich Raptor
55000
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct donors
{
string name;
double price = 0;
};
int main()
{
int no_donors = 0;
ifstream openFile;
openFile.open("FileInput.txt");
if (!openFile.is_open())
{
exit(EXIT_FAILURE);
}
openFile >> no_donors;
donors* b = new donors[no_donors];
while (openFile.good())
{
cout << "File opened sucessfully: ";
for (int i = 0; i < no_donors; i++)
{
getline(openFile, b[i].name);
(openFile >> b[i].price).get();
}
}
if (openFile.eof())
cout << "End of file has been reached.\n\n";
else if (openFile.fail())
cout << "Input terminated by data mismatch.\n\n";
else
{
cout << "Input terminated for unknown reason.\n";
openFile.clear();
cin.clear();
cin.get();
exit(EXIT_FAILURE);
}
for (int j = 0; j < no_donors; j++){
cout << b[j].name;
cout << b[j].price << endl;
}
delete[] b;
cin.get();
cin.get();
return 0;
}
My program seems to have read the information in from the file however the problems here as this piece of code is not working.
Code:
for (int j = 0; j < no_donors; j++){
cout << b[j].name;
cout << b[j].price << endl;
}
Does anyone know why?