2011-07-28 53 views
2

我在修改C中的数组时遇到了一些问题。我有两个数组,c1和c2。C中的char数组?

我想通过键入单词数组c1包含的单词来手动填充数组c2。用户键入一个字母,如果在c1中找到这个字母,程序会在c2的适当位置修正这个字母。如果该信件不属于C1,则它什么都不做。这就像一个“猜词”游戏。这里是一个草图:

c1 = MARRON 

c2: ****** 
Type a letter: E 


c2: ****** 
Type a letter: A 


c2: *A**** 
Type a letter: O 


c2: *A**O* 
Type a letter: P 


c2:*A**O* 
Type a letter: M 


c2: MA**O* 
Type a letter: N 


c2: MA**ON 
Type a letter: R 

c2: MARRON 

You win. 

我的代码并没有真正遵循上面的草图。我的问题是在正确的时间打印星号和字母。我还发现该程序用星号替换了最后一个字符,尽管我保留了一个条件来防止这种情况发生。 Here'my code:

void complete(char *c2, char c1[], int letter) { 
    int i = 0; 
    for(i = 0; i < strlen(c1) - 1; i++) 
     if(c1[ i ] == '\0') { 
      c2[ i ] = '\0'; 
     } 
     else if(letter != c1[ i ] && c2[ i ] != '*'); 



     else if (letter == c1[ i ]) { 
      c2[ i ] = letter; 
      c2[ i + 1 ] = '\0'; 
     } 
     else if (letter != word[ i ]) 
      c2[ i ] = '*'; 
    c2[ i + 1 ] = '\0'; 
} 

int main(){ 
    char c1[] = "ORANGE"; 
    int length = strlen(c1); 

    char *c2 = NULL; 
    c2 = malloc(length * (sizeof(c1)); 

    while(1){ 
     printf("What is the secret word?: "); 
     printf("%s\n", c2); 
     printf("Propose a letter: "); 
     letter = lirecaracter();//it just reads a character 

     char *suite = NULL; 
     suite = strchr(c1, letter); 
     if(suite != NULL){ 
      complete(c2, c1, letter); 
     } 

     if(strcmp(c1, c2) == 0){ 
      printf("\n You won, congrats\n"); 
      exit(0); 
     } 

    } 

} 

谢谢。

+1

这是功课?如果需要,您需要标记 –

+0

如果在if之前,您的第一个循环很奇怪,也strlen实际返回字符串的正确长度不需要-1 – Pepe

+0

@andreas:不,它不是作业 – mkab

回答

7

伪代码:

WordGuessGame(target[1..n], buffer[1..n], input[1..m]) 
    1. for i := 1 to n do 
    2. buffer[i] := '*' 
    3. print buffer 
    4. for i := 1 to m do 
    5. for j = 1 to n do 
    6.  if target[j] = input[i] then 
    7.   buffer[j] := input[i] 
    8. if buffer = target then 
    9.  print "You win!" 
    10.  return 
    11. else print buffer 
    12. print "You lose..." 
+0

Phew。我终于明白了你的代码。谢谢你的帮助。 – mkab

0

为您的家庭作业的解决方案是非常简单的,如:

int main(){ 
    char *p,c,*c1 = "ORANGE", c2[]="******"; 

    while(puts(c2),strcmp(c1,c2)) 
    { 
     printf("Propose a letter: "); 
     c=getchar(); while(getchar()!='\n'); 
     p=c1; 
     while(*p) 
     if(*p++==c) c2[p-c1-1]=c; 
    } 

    printf("\n You won, congrats\n"); 
    return 0; 
}