2014-03-31 26 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