2014-09-26 169 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]); 
    } 
} 
相关问题