C++流不写入输出文件
C++ ofstream not writing to output file?
代码应该计算输入文本文件中a,b,c,d,e和f字符的数量,并将输出打印到第二个文本文件中。当我运行代码时,它会创建输出文件,但不在其中写入任何内容。
#include<iostream>
#include<fstream>
#include<cmath>
using namespace std;
int main(){
// establish counters for the number of each character
char x;
int acount=0;
int bcount=0;
int ccount=0;
int dcount=0;
int ecount=0;
int fcount=0;
ifstream iFile("plato.txt"); //define & open files
ofstream oFile("statistics.txt");
if(!iFile){
cout<<"The file could not be opened.";
exit(1);
}
if(!oFile){
cout<<"The file could not be opened.";
exit(1);
}
iFile>>x;
while(!iFile.eof()){
if(x=='a'||x=='A'){
acount++;
}
else if(x=='b'||x=='B'){
bcount++;
}
else if(x=='c'||x=='C'){
ccount++;
}
else if(x=='d'||x=='D'){
dcount++;
}
else if(x=='d'||x=='D'){
dcount++;
}
else if(x=='f'||x=='F'){
fcount++;
}
}
oFile<<"Number of a/A characters: "<<acount; //write number of characters into statistics file
oFile<<"nNumber of b/B characters: "<<bcount;
oFile<<"nNumber of c/C characters: "<<ccount;
oFile<<"nNumber of d/D characters: "<<dcount;
oFile<<"nNumber of e/E characters: "<<ecount;
oFile<<"nNumber of f/F characters: "<<fcount;
//close files
iFile.close();
oFile.close();
}
你有一个无限循环; 你在循环中不做任何会改变ifile.eof()
状态的事情。 当然,这个条件一开始就是错误的——你永远不想ios_base::eof()
用作循环中的条件。 您的循环可能应该是:
while ( iFile >> x ) {
,尽管对于读取单个字符,使用 get
可能更简单。
在 while 语句(在其末尾)插入以下行:
iFile>>x;
以前,您只扫描了 x 的第一个值,因此 while 循环将永远持续下去。
相关文章:
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- VI工作室代码错误无法打开输出文件主.exe
- 在代码块中查找输出文件
- 将未签名的字符写入输出文件
- 为什么我的代码不写入输出文件?
- 完成搜索任务时为空输出文件
- 如何将地图<列表<string>、矢量<string>>输出到输出文件?
- 无法在代码块 IDE 中打开输出文件.exe
- C++:更改 IF 语句中的输出文件
- 编译 gsoap 输出文件 (onvif) 时出现问题
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- while 循环中的流输出文件() 通常生成空文件
- 如何使用 Docker 访问输出文件
- 提升进程间共享内存删除、权限和输出文件
- 查找素数,然后将质数放入输出文件中
- GDB / C++ - 根据循环条件将多个变量记录到输出文件中
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 我的输出文件未显示解决方案
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- C++,我正在尝试创建一个有效的.bmp输出文件