用C++编写文件
Writing out to a file in C++
这是我的代码:
#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");
当然,末尾的infile
和outfile
应该替换为实际的文件名。
您可以通过检查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();
}
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到