sách gpt4 ai đã đi

c++ - 使用try-catch C++处理文件

In lại 作者:行者123 更新时间:2023-11-28 06:17:30 33 4
mua khóa gpt4 Nike

我正在做一个关于文件处理的项目。用户输入 ID、小时数和工资率。输出将是 ID、小时数、工资率和总工资。我完成了那些部分。我真的需要关于 try and catch 的帮助,用户输入非数字,项目拒绝并要求用户再次输入。这是我到目前为止得到的:

#include 
#include
#include
#include
#include
#include "File.h"
#include
sử dụng không gian tên std;

void File::Create()
{
ofstream outClientFile("payroll.txt", ios::out);

if (!outClientFile)
{
cerr << "File could not be opened" << endl;
thoát(THOÁT_THẤT_CẦN);
}

cout << "Enter employee ID, hours and payrate" << endl
<< "Enter end-of-file to end input.\n? ";

while (cin >> id >> hours >> payrate)
{
thử
{
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;
thoát(THOÁT_THẤT_CẦN);
}

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;
}

测试文件

#include "File.h"

int chính()
{
File myFile;
myFile.Create();
myFile.Read();
}

1 Câu trả lời

你不应该使用异常,除非在“异常”情况下,程序不能轻易恢复(比如内存分配错误,打开文件时出错等)。使用 trong khi 循环可以更自然地完成验证输入,如下所示:

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
std::cin.ignore(std::numeric_limits::max(), '\n');
}
// now we can write the result to the file, input was validated
outClientFile << id << ' ' << hours << ' ' << payrate << endl;

nếu như cin 读取正确,那么它将转换为 bool ĐÚNG VẬY 并且循环不会被执行。如果不是(即一些非数字输入),则 cin >> ... 的最终结果将是一个转换为 SAI 的流。在后一种情况下,您需要清除错误标志(std::cin.clear() 部分),然后删除流中剩余的其余字符(std::cin .ignore() 部分)并重复。

关于c++ - 使用try-catch C++处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29979415/

33 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com