#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;//count
int c;//for EOF test
int menu;
unsigned int firstSize = 12811;
unsigned int lastSize;
char * text=malloc(firstSize);
if(text == NULL){
printf("\n Error. no Allocation.");
exit(-1);
}
printf("\n for input 1e,for autoinput press 2.");
scanf("%d",&menu);
if(menu==1){
printf("enter text..");
c = EOF;
i = 0;
lastSize = firstSize;
while (( c = getchar() ) != '\n' && c != EOF)
{
text[i++]=(char)c;
//if i reached maximize size then realloc size
if(i == lastSize)
{
lastSize = i+firstSize;
text = realloc(text, lastSize);
}
}
这是问题所在的代码部分。
当我输入
1
时输出为 scanf
是:for input 1e,for autoinput press 2.
1
enter text..
它不允许我为
getchar()
提供输入.但是当我删除
scanf
为 menu
并使用 menu=1;
,我可以轻松地为 getchar()
提供输入它给了我正确的输出:printf("\n for input 1e,for autoinput press 2.");
scanf("%d",&menu);
而不是那个
printf("\n for input 1e,for autoinput press 2.");
//scanf("%d",&menu);
menu=1;
是关于
printf
scanf
我不知道的问题?在java中,在进行第二次输入之前,我们需要放一些空白。是这样吗?
最佳答案
问题是您在输入 scanf
的数字后按 Enter 键。 .该号码由 scanf
消耗而由回车键生成的换行符驻留在标准输入流( stdin
)中。
当程序执行到while
环形:
while (( c = getchar() ) != '\n' && c != EOF)
getchar()
看到换行符,捕获它,把它分配给 c
然后,循环不会执行,因为条件( c != '\n'
)为假。这是你始料未及的。你可以加
while (( c = getchar() ) != '\n' && c != EOF);
scanf
之间的任何位置和您的 getchar()
清除 stdin
.另一种方法是使用
scanf("%d%*c",&menu);
正如 @user3121023 所建议的in the comments . %*c
指示scanf
读取和丢弃一个字符。如果用户输入了一个数字,然后为 scanf
按下回车键,它将丢弃换行符。 .其他的东西:
c = EOF;
不是必需的。 Actor 也不在这里:text[i++]=(char)c;
.您也不需要两个变量 lastSize
和 firstSize
.您还应该检查 realloc
的返回值.
关于C、无法读取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31219776/