我正在編寫一個程序(用於班級作業),以將普通單詞翻譯爲其等值的海盜(hi = ahoy)。從文本文件中讀取單個單詞並翻譯 - C
我已經使用兩個字符串數組創建了字典,現在正在嘗試翻譯一個input.txt文件並將其放入output.txt文件中。我可以寫入輸出文件,但它只能將翻譯的第一個單詞反覆寫入新行。
我已經做了很多閱讀/沖刷,從我所知道的情況來看,使用fscanf()
來讀取我的輸入文件並不理想,但我無法弄清楚什麼是更好的函數。我需要逐字讀取文件(用空格分隔)並讀取每個標點符號。
輸入文件:
Hi, excuse me sir, can you help
me find the nearest hotel? I
would like to take a nap and
use the restroom. Then I need
to find a nearby bank and make
a withdrawal.
Miss, how far is it to a local
restaurant or pub?
輸出:嗨(46次,每次一個單獨的行)
翻譯功能:
void Translate(char inputFile[], char outputFile[], char eng[][20], char pir[][20]){
char currentWord[40] = {[0 ... 39] = '\0'};
char word;
FILE *inFile;
FILE *outFile;
int i = 0;
bool match = false;
//open input file
inFile = fopen(inputFile, "r");
//open output file
outFile = fopen(outputFile, "w");
while(fscanf(inFile, "%s1023", currentWord) == 1){
if(ispunct(currentWord) == 0){
while(match != true){
if(strcasecmp(currentWord, eng[i]) == 0 || i<28){ //Finds word in English array
fprintf(outFile, pir[i]); //Puts pirate word corresponding to English word in output file
match = true;
}
else {i++;}
}
match = false;
i=0;
}
else{
fprintf(outFile, &word);//Attempt to handle punctuation which should carry over to output
}
}
}
非常感謝!這固定了它。另外,謝謝你解釋爲什麼我的代碼不工作。希望我現在可以避免這個錯誤。 – bullinka 2014-09-26 03:57:52