2014-09-26 165 views
-1

我正在編寫一個程序(用於班級作業),以將普通單詞翻譯爲其等值的海盜(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 


    } 

} 

} 

回答

0

當開始針對不同英語單詞匹配, i<28最初是正確的。因此,表達式<anything> || i<28也立即成立,相應地,代碼的行爲就像在字典中的第一個單詞上找到匹配一樣。

爲了避免這種情況,您應該分別處理「找到匹配項i」和「找不到匹配項」條件。這是可以實現如下:

if (i >= dictionary_size) { 
    // No pirate equivalent, print English word 
    fprintf(outFile, "%s", currentWord); 
    break; // stop matching 
} 
else if (strcasecmp(currentWord, eng[i]) == 0){ 
    ... 
} 
else {i++;} 

其中dictionary_size將你的情況28(根據您在使用i<28停止狀態的嘗試)。

+0

非常感謝!這固定了它。另外,謝謝你解釋爲什麼我的代碼不工作。希望我現在可以避免這個錯誤。 – bullinka 2014-09-26 03:57:52

0

下面是我用來解析事情的代碼片段。下面介紹一下它的作用:

鑑於此輸入:

hi, excuse me sir, how are you. 

它把每個字爲基礎上,不斷DELIMS字符串數組,並刪除DELIMS const的任何字符。這將破壞您的原始輸入字符串。我簡單地打印出的字符串數組:

[hi][excuse][me][sir][how][are][you][(null)] 

現在,這個正在從標準輸入,但你可以改變周圍的它把它從文件流。你也可能想要考慮輸入限制等。

#include <stdio.h> 
#include <string.h> 
#define CHAR_LENGTH   100 

const char *DELIMS = " ,.\n"; 
char *p; 
int i; 

int parse(char *inputLine, char *arguments[], const char *delimiters) 
{ 
    int count = 0; 
    for (p = strtok(inputLine, delimiters); p != NULL; p = strtok(NULL, delimiters)) 
    { 
     arguments[count] = p; 
     count++; 
    } 
    return count; 
} 

int main() 
{ 
    char line[1024]; 
    size_t bufferSize = 1024; 

    char *args[CHAR_LENGTH]; 

    fgets(line, bufferSize, stdin); 
    int count = parse(line, args, DELIMS); 
    for (i = 0; i <= count; i++){ 
     printf("[%s]", args[i]); 
    } 
} 
相關問題