2014-03-31 25 views
0

對於家庭作業的一部分,我需要循環提示,讓用戶輸入單詞,直到他們輸入20個單詞或直到他們輸入單詞'done'。目前,我對這兩個參數都滿意,但是如果我輸入'done'這個詞,它也會被掃描到數組中,這不是我想要做的。C中的字符串數組

這是我的當前功能:

int row = 0; 
int column = 0; 
int i = 0; 

while(i < 20) 
    { 
     printf("Enter words you would like hidden in the puzzle. Type 'done' when finished:\n"); 
     scanf("%s",a[i]); 

     if(strcmp(a[i],"done") == 0) 
     { 
     break; 
     } 

     if((strlen(a[i]) > row) || (strlen(a[i]) > col)) 
     { 
     printf("Error. Word was too long to enter into puzzle.\n"); 
     } 

     else 
     { 
     i++; 
     } 
    } 

陣列 'a' 是字符串的數組。我知道行scanf("%s",a[i]);正在將單詞'done'掃描到數組中,我只是不知道如何調整它,以免發生。 有人可以幫我指出這部分嗎?

+0

你覺得什麼'的scanf( 「%s」 時,A [1]);'行是幹什麼的? – FDinoff

+2

什麼是「a」。數組? –

+1

你可以在你的「完成」'if'中做'i - ;'。或者你可以根據'a'的類型和''while''來做'a [i] = NULL'。 – Biduleohm

回答

1

試試這個:

char input[256]; 
while(i < 20) 
{ 
    printf("Enter words you would like hidden in the puzzle. Type 'done' when finished:\n"); 
    scanf("%s",&input); 
    if(strcmp(input,"done") != 0) 
    { 
    strcpy(a[i],input); 
    if((strlen(a[i]) > row) || (strlen(a[i]) > col)) 
    { 
     printf("Error. Word was too long to enter into puzzle.\n"); 
    } 
    i++; 
    } 
    else 
    break; 
} 
+0

什麼是'string'? –

+0

@MattMcNabb:曾經是一名c#程序員。 :-)無論如何,編輯我的答案。謝謝。 –

+0

我想你可能需要一個'strcpy'而不是'a [i] = input'。此外,我認爲'scanf(「%s」,輸入);'不'scanf(「%s」,&輸入);'。 – ssm