I'm doing 9th exercise of 6th chapter from C++ Primer Plus book, and, I've got some problem with reading from a file. It must be something wrong with operator >> and getline, but I don't know what, and how to deal with that. I would be really grateful if somebody could tell me what I should do in that case.
Here is the exercise:
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
The file "Contribution.txt" contains the same names and values as in exercise. The output is, it displays 4x no names and $0.
Here is the code:
#include <iostream>
#include <fstream> //file I/O support
#include <cstdlib> //support for exit()
#include <string>
std::string name;
double contr;
int content;
int i=0;
int main()
{
std::ifstream inFile; // object for handling file input
inFile.open("Contribution.txt");
if (!inFile.is_open()) // failed to open file
{
std::cout <<"Could not open the file \"Contribution.txt\""<<std::endl;
std::cout <<"Programing terminating.\n";
exit(EXIT_FAILURE);
}
inFile>>content;
if(inFile.good())
{
while(i<content)
{
getline(inFile,name); //saves the line in string name
inFile>>contr; //saves value in double contr
std::cout<<name<<std::endl;
std::cout<<"$"<<contr<<std::endl;
i++;
}
}
if(inFile.eof())
std::cout<<"End of file reached.\n"<<std::endl;
else if(inFile.fail())
std::cout<<"Input terminated by data mismatch.\n";
else
std::cout<<"Input terminated for unknown reason.\n";
inFile.close();
return 0;
}
When it finishes it returns:
Input terminated by data mismatch.