C - 循环不会中断
我希望当按下“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;
}
I want the loop to break when "Enter" is pressed. Any suggestions?
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
scanf
调用读取第一个字符,然后您的read_word
函数会覆盖它。如果scanf
调用读取换行符,它将被忽略。这些行:
... 也显得错误。
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;
而不是当前的赋值。Your
scanf
call reads the first character, and then yourread_word
function overwrites it. If thescanf
call reads the newline, it will then be ignored.The lines:
... also appears wrong.
read_word
returns an integer (the length of the string read), but you are storing into achar
array. Also, you are re-allocating the memory forp
each time through the loop, so the values stored previously will be lost.To fix:
p
to be anint *
, and initialize it to nullmalloc
call to a suitablerealloc
scanf
entirelyp == null
before the assignment of `p = (char*) malloc(nwords*sizeof(char));'Or: is
p
meant to actually be an array of strings (the words themselves) rather than the word length? In that case you have to:p
to be anchar **
realloc
call) tonwords * sizeof(*p)
malloc
) storage for each word instead of havingword
be a stack-allocated arrayp[i] = word;
rather than the current assignment.