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(){
//为每个字符的数字建立计数器
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&打开文件
ofstream oFile(statistics.txt);
if(!iFile){
cout<<无法打开文件。
exit(1);
}
if(!oFile){
cout<<无法打开文件。
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; //将数字写入统计文件
oFile<<\\\
数字b / B字符:<< bcount;
oFile<<\\\
个c / C字符数:<< ccount;
oFile<<\\\
数字d / D字符:<< dcount;
oFile<<\\\
e / E字符数:<< ecount;
oFile<<\\\
F / F字符数:<< fcount;
//关闭文件
iFile.close();
oFile.close();
}
循环;你在循环中什么也不做,这会改变 ifile.eof()
的状态。当然,条件是错误的开始—你永远不想使用 ios_base :: eof()
作为循环中的条件。您的循环应该是:
while(iFile>> x){
,但是对于读取单个字符,使用 get
可能更简单。 >
The code is supposed to count the number of a, b, c, d, e, and f characters in the input text file and print the output into a second text file. When I run the code, it creates the output file but doesn't write anything into it.
#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();
}
You've got an endless loop; you do nothing in the loop which would change the state of ifile.eof()
. And of course, the condition is wrong to begin with—you never want to use ios_base::eof()
as the condition in a loop. Your loop should probably be:
while ( iFile >> x ) {
, although for reading single characters, it might be simpler to use get
.
这篇关于C ++的流不写输出文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!