退出没有break语句的循环?

时间:2014-04-03 00:49:47

标签: c arrays loops multidimensional-array

对于家庭作业,我需要提示用户输入单词,直到他们输入20个单词或输入“完成”字样。现在我有一个带有while循环的函数,它可以扫描输入的每个单词,但是当用户键入' done'时,循环不会结束。

功能:

int wordentry(int row, int col, char a[20][100])

{

int i = 0;/* Counter */


    printf("Enter 20 words you would like hidden in the puzzle, or type 'done' when finished:\n");

    /* While the user hasn't entered 20 words, or the user hasn't entered the word 'done' the prompt to enter words keeps looping */

    while(i < 20)
    {
      scanf("%c",a[i]);
      if(strcmp(a[i],"done") == 0)
      {
        return(i);
      }
      i++;

    }/* Ends while loop */



return(i);

}/* Ends function */

变量row是用户确定的变量,是每个单词插入的单词搜索拼图的行长度,变量col是用户确定的每列长度。数组a是每个单词存储为字符串的位置。返回变量i用于跟踪用户输入的单词数。另外,除非有switch语句,否则我无法使用任何break语句。我感到沮丧,因为我无法弄清楚如何做到这一点。有人可以帮忙吗?

4 个答案:

答案 0 :(得分:3)

scanf只读取%c表示的单个字符。所以比较是比较&#39; d&#39;完成&#34;完成&#34;这是不平等的。使用%s以便输入整个单词,然后继续调试问题。

  scanf("%s",a[i]);

  if(strcmp(a[i],"done") == 0)
  ... 

答案 1 :(得分:2)

我认为if语句中的strcmp总是返回false。我对C编程语言没有很好的经验,但是试着把这样的东西放到这样的

...
scanf("%s",&a[0]);
if(strcmp(a[i],"done") == 0)
...

(别忘了包含string.h)

答案 2 :(得分:0)

要在没有break语句的情况下退出循环,您需要满足保持循环运行的条件。所以当你有以下内容时:

while (i < 20)

i设置为20或更高将使循环不再执行。一个区别是它将继续到当前运行的结束而不是立即退出。

答案 3 :(得分:0)

避免冗余和硬编码值,任何改变控制流的条件都值得明确,所以避免goto,continue和break(除了在switch语句中)并且字符很便宜,所以给你的变量一些有意义的名字:< / p>

#define MAXWORDS 20
#define MAXCHARS 99

int wordEntry(int row, int col, char words[MAXWORDS][MAXCHARS+1])
{

    int numEntered = 0;
    int userDone = 0;
    char *doneWord = "done";

    printf("Enter %d words you would like hidden in the puzzle, or type '%s' when finished:\n", MAXWORDS, doneWord);

    /* While the user hasn't entered max words, or the user hasn't entered the word 'done' the prompt to enter words keeps looping */

    while( !userDone && (numEntered < MAXWORDS) )
    {
        scanf("%s",words[numEntered]);
        if (strcmp(words[numEntered],doneWord) == 0)
        {
            userDone = 1;
        }
        else
        {
            numEntered++;
        }

    }/* Ends while loop */

    return numEntered;

}/* Ends function */

在决定使用scanf()之前,请先阅读http://c-faq.com/stdio/scanfprobs.html