【问题标题】:C - Loop won't breakC - 循环不会中断
【发布时间】:2011-05-07 10:04:53
【问题描述】:

我希望在按下“Enter”时循环中断。有什么建议吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define len 20
#define limit 100

//Prototypes for functions
int read_word(char str[], int n);



int main(void)
{
  char *p;
  char word[len+1];
  int i=0, nwords = 0;

//Loop for reading in words and allocating an array 
  for (;;)
   {
      if (nwords == limit)
       {
          printf("Insufficient Space\n");
          break;
       }
      printf("Enter word: ");
      scanf("%c", &word);
      p = (char*) malloc(nwords*sizeof(char));
      p[i]= read_word(word, len);
      i++;

      if (p == NULL)
      {
          printf("Insufficient Space\n");
          break;
      }
  }

  for(i=0; i<nwords; i++)
      printf(" %s\n", p[i]);

  return 0;

  } 
int read_word(char str[], int n)
{
  char ch; 
  int i = 0;

  while((ch = getchar()) != '\n')
      if (i<n)
          str[i++] = ch; 
  str[i] = '\0';
  return i;
}

【问题讨论】:

  • 您在哪里测试是否按下了 Enter 键?
  • 您还在检查p 指针是否为NULL 太晚了——在使用它之后。
  • 我相信它在 read_word 函数中。应该是 while 循环的控制表达式。

标签: c string loops


【解决方案1】:

您的scanf 调用读取第一个字符,然后您的read_word 函数将其覆盖。如果scanf 调用读取了换行符,它将被忽略。

线条:

  p = (char*) malloc(nwords*sizeof(char));
  p[i]= read_word(word, len);

... 也出现错误。 read_word 返回一个整数(读取的字符串的长度),但您将存储到 char 数组中。此外,您每次通过循环都为p 重新分配内存,因此之前存储的值将丢失。

修复:

  • p更改为int *,并将其初始化为null
  • malloc 调用更改为合适的realloc
  • 完全删除对scanf的调用
  • 移动检查p == null分配`p = (char*) malloc(nwords*sizeof(char));'之前

或者:p 实际上是一个字符串数组(单词本身)而不是单词长度?在这种情况下,您必须:

  • p 更改为char **
  • 将分配大小(用于realloc 调用)更改为nwords * sizeof(*p)
  • 为每个单词分配(使用malloc)存储空间,而不是让word 成为堆栈分配的数组
  • 设置p[i] = word; 而不是当前分配。

【讨论】:

  • 因此,通过将 p 更改为 int 指针数组,我将能够将字符串存储到元素中,然后递增指针以访问它?
  • 是的,我想将单词作为字符串存储到数组中,然后能够访问单个单词
  • @Richard,没有。要将字符串存储到元素中,元素类型应为char *(或char[])。请参阅我(已编辑)答案的最后一部分。
  • @Richard 那么您需要将 p 更改为 char **,即指向字符串的指针,而不是指向字符的指针。另请注意,您仍然需要删除对scanf 的调用,将现有的malloc 更改为realloc,并移动空指针检查。
  • 啊,明白了。谢谢,帮了大忙!
猜你喜欢
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多