我希望在按下“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;
}
最佳答案
您的 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;
而不是当前的赋值。
关于C - 循环不会中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5920381/