C、无法读取输入

标签 c input getchar

#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() 提供输入.

但是当我删除 scanfmenu并使用 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; .您也不需要两个变量 lastSizefirstSize .您还应该检查 realloc 的返回值.

关于C、无法读取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31219776/

相关文章:

c - http 请求未收到完整信息 - C

c - 多个 char* 比较的段错误

java - 我如何知道点击了哪个提交按钮

java - 如何使用 Android 按钮获取整数作为用户输入?

c - 这个C函数有什么问题? (printf() 和 getchar())

将 float 数据转换为必须通过 UDP 发送的 Char 数据

c - 有没有办法将条件分配转换为无分支代码?

javascript - 如何使用 onClick 写入文本文件?

c - 为什么使用多个 "if"s 不起作用,但在 while 循环中使用 "if"s 和 "else if"s 却起作用?

c - 模拟 getchar() 的 UART 驱动程序