问题
I'm working on a project about file processing. The users input ID, hours, and payrate. The output will be ID, hours, payrate and grosspay. I got those parts done. I really need help on try and catch, where users input a non-numeric, the project rejects and ask users to input again. Here what I got so far:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include "File.h"
#include <exception>
using namespace std;
void File::Create()
{
ofstream outClientFile("payroll.txt", ios::out);
if (!outClientFile)
{
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
}
cout << "Enter employee ID, hours and payrate" << endl
<< "Enter end-of-file to end input.\n? ";
while (cin >> id >> hours >> payrate)
{
try
{
outClientFile << id << ' ' << hours << ' ' << payrate << endl;
cout << "? ";
}
catch (exception elementException)
{
cerr << ("Invalid input. Try again") << endl;
}
}
}
void outputLine(int, float, float, float);
void File::Read()
{
ifstream inClientFile("payroll.txt", ios::in);
if (!inClientFile)
{
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
}
cout << left << setw(15) << "Employee ID" << setw(15) << "Hours" << setw(15) << "Payrate" << setw(15) << "Grosspay" << endl << fixed << showpoint;
while (inClientFile >> id >> hours >> payrate)
outputLine(id, hours, payrate, grosspay = hours * payrate);
}
void outputLine(int id, float hours, float payrate, float grosspay)
{
cout << left << setw(7) << id << setprecision(2) << setw(8) << " , " << setw(8) << hours << setprecision(2) << setw(7)
<< " , " << "$" << setw(7) << payrate << setprecision(2) << setw(7) << " , " << "$" << grosspay << right << endl;
}
TEST FILE
#include "File.h"
int main()
{
File myFile;
myFile.Create();
myFile.Read();
}
回答1:
You should not use exceptions unless in "exceptional" cases, where the program cannot easily recover (like a bad memory allocation, error opening a file etc). Validating input can be done much more naturally with a while
loop, like so:
while( ! (std::cin >> id >> hours >> payrate) ) // repeat until we read correctly
{
std::cout << "Invalid input, try again..." << std::endl;
std::cin.clear(); // clear the error flags
// ignore the rest of the stream, must #include <limits>
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
// now we can write the result to the file, input was validated
outClientFile << id << ' ' << hours << ' ' << payrate << endl;
If cin
reads correctly, then it will convert to bool
true
and the loop will not be executed. If not (i.e. some non-numeric input), then the end result of cin >> ...
will be a stream which converts to false
. In this latter case, you need to clear the error flags (std::cin.clear()
part), then erase the rest of the characters left in the stream (std::cin.ignore()
part) and repeat.
来源:https://stackoverflow.com/questions/29979415/file-processing-using-try-catch-c