用C++编写文件

Writing out to a file in C++

本文关键字:文件 C++      更新时间:2023-10-16

这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string fname,lname;
double pincrease //pay increase percentage,pay;
ifstream infile;
ofstream outfile;
infile.open("C:\Users\Connor\Desktop");
outfile.open("C:\Users\Connor\Desktop");
while(!infile.eof())
{
infile>>lname>>fname>>pay>>pincrease;
pay = pay*(pay*pincrease);
outfile<<fname<<" "<<lname<<" "<<pay<<"n";
cin.clear();
}
infile.close();
outfile.close();
}

以下是我的infile:的内容

Miller Andrew 65789.87 5
Green Sheila 75892.56 6
Sethi Amit 74900.50 6.1

该信息采用Last Name:First Name:Pay:Pay Increase Percentage的形式。

当我写信给outfile时,名字和姓氏的顺序交换以及支付百分比增加的排除是有意的。

我正在尝试读取infile的内容,对其进行修改,然后将其写入outfile

然而,当我执行代码时,我开始了一个我很确定的无限循环,但我不确定如何修复它

这两条语句都不可能打开文件:

infile.open("C:\Users\Connor\Desktop");
outfile.open("C:\Users\Connor\Desktop");

相反,他们尝试(很可能失败)打开您的Desktop文件夹。相反,你可能想要更像的东西

infile.open("C:\Users\Connor\Desktop\infile");
outfile.open("C:\Users\Connor\Desktop\outfile");

当然,末尾的infileoutfile应该替换为实际的文件名。

您可以通过检查infile.is_open()outfile.is_open()来测试文件打开是否成功。您可以添加显式if语句来测试这一点:

if (!infile.is_open())
// report/handle that you couldn't open input file
if (!outfile.is_open())
// report/handle that you couldn't open output file

对于你的主循环,你不应该像现在这样测试eof

while(infile>>lname>>fname>>pay>>pincrease)
{
pay = pay*(pay*pincrease);
outfile<<fname<<" "<<lname<<" "<<pay<<"n";
cin.clear();
}

以您原来的方式测试EOF将尝试读取文件末尾以外的一条额外记录。

只有在读取尝试失败后,才会设置EOF标志。因此,你应该总是在尝试阅读后测试EOF。

标准ifstream以这样的方式设置,即典型的ifstream输入操作(即infile >> item)将返回对ifstream对象的引用。这就是你可以做infile >> item1 >> item2 >> item3之类的事情的方法。

当您将其放在循环控件的上下文中时(如上所述),ifstream具有适当的运算符重载,使其根据读取是否成功来告诉while是否保持循环。

其他人已经在其他地方很好地解释了超负荷魔术。关于循环终止魔法的更多信息:为什么istream对象可以用作布尔表达式?

更换此

infile.open("C:\Users\Connor\Desktop");
outfile.open("C:\Users\Connor\Desktop");

用这个

infile.open("C:\Users\Connor\infile.txt");
outfile.open("C:\Users\Connor\outfile.txt");

您发布的代码将不会编译,原因有两个。第一,变量pay尚未声明;第二,您已经注释掉了以下代码的终止。

double pincrease //pay increase percentage,pay;

请尝试以下代码。希望它能帮助

int main()
{
string fname,lname;
double pincrease; //pay increase percentage,pay;
double pay;
ifstream infile;
ofstream outfile;
infile.open("C:\Users\Connor\infile.txt");
outfile.open("C:\Users\Connor\outfile.txt");
while(!infile.eof())
{
infile>>lname>>fname>>pay>>pincrease;
pay = pay*(pay*pincrease);
outfile<<std::setprecision(2)<<std::showpoint << std::fixed;;
outfile<<fname<<" "<<lname<<" "<<pay<<"n";
cin.clear();
}
infile.close();
outfile.close();
}