[英]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循環永遠持續。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.