C++循环算法不正确(或文件处理问题)
C++ Incorrect Looping Algorithm (or file processing issue)
我正在尝试制作一个程序,读取文本文件,进行一些数学运算,显示答案,然后编写文本文件。该程序目前只写一行文本,而不是我想要的5行。
输入文本文件的格式如下:
string double double
string double double
string double double
string double double
string double double
输出文本文件变为:字符串,双,双,双重,
它写我想要的东西,但只有一次。我希望它能处理所有5行。我的程序只处理输入文本文件的最后一行。
这就是输入文本文件的样子(只是没有文件名)
//payinfile.txt
2198514 17.20 11.25
6698252 59.25 21.00
5896541 50.00 10.00
8863214 45.00 18.20
8465555 25.75 14.80
这是我的程序的代码
// outputprogram.cpp
#include <iostream>
#include <fstream> // file stream
#include <iomanip>
#include <string>
#include <cstdlib> // exit function prototype
using namespace std;
void outputLine(const string, double, double); // prototype
// void writeToFile();
int main()
{
// ifstream constructor opens the file
ifstream inputFile("payinfile.txt", ios::in);
// exit program if ifstream could not open file
if (!inputFile)
{
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
} // end if
string ID; // the account number
double hours; // the account owner's name
double rate; // the account balance
cout << left << setw(10) << "ID" << setw(15)
<< "Hours" << setw(10) << "Rate" << right << setw(10) << "Gross" << endl << fixed << showpoint;
// display each record in file
while (inputFile >> ID >> hours >> rate)
{
outputLine(ID, hours, rate);
}
} // end main
// display single record from file
void outputLine(const string ID, double hours, double rate)
{
double gross;
gross = 0.0;
gross = (hours * rate);
cout << left << setw(10) << ID
<< setw(15) << hours
<< setw(15) << setprecision(2) << rate
<< setw(10) << setprecision(2) << gross << endl;
// ofstream constructor opens file
ofstream writeToFile("FinalOutput.txt", ios::out);
// exit program if unable to create file
if (!writeToFile) // overloaded ! operator
{
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
} // end if
writeToFile << ID << ", " << hours << ", " << rate << ", " << gross << ", ";
} // end function outputLine
执行后,输出文件如下所示:
//FinalOutput.txt
8465555, 25.75, 14.8, 381.1,
所以它写了我想要的,我只想它也把其他4行写到FinalOutput.txt
在行中:
ofstream writeToFile("FinalOutput.txt", ios::out);
每次要写一行时,都会打开输出文件。这将截断文件(即删除内容)。
您可以每次以追加模式打开文件,或者更好的是,在函数外打开一次文件,然后通过引用将流对象传递到outputLine
函数中。
相关文章:
- posix_spawn():使用posix_scawn()时的错误处理问题
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- 用户输入字符串的文件附加问题..C++
- 出色的文件处理能力
- C++中的文件处理:更新行
- 我遇到使用 c++ 逐行读取输入文件的问题
- 文件处理,eof() 定义
- 使用 fstream 库并在屏幕上打印的文件有问题?
- Win7 C++ - 从以用户身份登录的服务启动可执行文件的问题
- 尝试使用 Ifstream 打开.txt文件时C++问题
- 有关在C++中解析二进制文件的问题
- C++网络 IO、文件处理和网络故障
- LittleFS文件系统,NOR闪存的文件写入问题
- 关于从驱动器中删除文件的问题
- LZMA c++ 压缩大文件的问题
- STD :: FSTREAM文件处理重复使用的问题
- C++循环算法不正确(或文件处理问题)
- Borland c++5.02文件处理问题
- c++中的文件处理代码有什么问题
- fstream打开在处理较大的文件时有问题吗?