C语言无法读取输入

4
#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);
        }
    }

这段代码是问题所在的部分。

当我在scanf中输入1时,输出结果为:

for input 1e,for autoinput press 2.
1
enter text..

我无法为getchar()提供输入。

但是当我删除menuscanf并使用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;

这是关于printfscanf问题的吗?在Java中,在输入第二个参数之前,我们需要输入一些空格。这是类似的吗?


1
请发布包含scanf的代码,以便更好地定位问题。请对齐代码。 - P.P
1
你知道这段Java代码存在什么问题吗:Scanner input = new Scanner(System.in); String str1 = input.nextLine(); String str2 = input.nextLine();?如果是的话,这个问题和之前一样。 - Spikatrix
1个回答

1
问题在于你在输入数字后按下了Enter键。数字被scanf函数读取,而由Enter键生成的换行符留存在标准输入流(stdin)中。

当程序执行到while循环时:

while (( c = getchar() ) != '\n' && c != EOF)

getchar()函数读取到换行符时将其从缓冲区中获取,将其赋值给变量c,此时循环不再执行,因为条件(c != '\n')不成立。这是你没有预料到的。


您可以添加。
while (( c = getchar() ) != '\n' && c != EOF);

scanfgetchar()之间的任何位置,都可以清除stdin

另一种方法是使用建议中的scanf("%d%*c",&menu);,建议来自@user3121023 评论中%*c指示scanf读取并丢弃一个字符。如果用户输入了数字,然后按下Enter键,则它将丢弃换行符。


其他内容:

c = EOF; 不是必需的。这里也不需要强制转换:text[i++]=(char)c;。你也不需要两个变量 lastSizefirstSize。你还应该检查 realloc 的返回值。


1
我需要为初始数组分配一个初始大小。如果不进行分配,我就无法将变量分配给数组。 - CursedChico
1
@CursedChico 是的。你只需要一个变量。为什么要两个?移除 lastSize 并将 lastSize = i+firstSize; 改为 firstSize = i+firstSize; 或者 firstSize = firstSize*2; - Spikatrix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接