【问题标题】:C, can not read inputC、无法读取输入
【发布时间】:2015-07-04 10:54:42
【问题描述】:
#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() 提供输入。

但是当我为menu 删除scanf 并使用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中,在进行第二次输入之前,我们需要放一些空白。是这样的吗?

【问题讨论】:

  • 发布代码 with 给出问题的 scanf。请对齐代码。
  • 你知道这段Java代码有什么问题吗:Scanner input = new Scanner(System.in); String str1 = input.nextLine(); String str2 = input.nextLine();?如果是这样,这是同样的问题。

标签: c input getchar


【解决方案1】:

问题是您在输入scanf 的数字后按Enter。该数字由scanf 使用,而回车键生成的换行符驻留在标准输入流中(stdin)。

当程序执行到while循环时:

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

getchar() 看到换行符,抓住它,将其分配给c,然后循环不执行,因为条件(c != '\n')为假。这是你没想到的。


你可以添加

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

scanf 和您的getchar() 之间的任意位置以清除stdin。

另一种方法是按照@user3121023in the comments 的建议使用scanf("%d%*c",&amp;menu);。 %*c 指示 scanf 读取并丢弃一个字符。如果用户输入了一个数字然后按回车键输入scanf,它将丢弃换行符。


其他东西:

c = EOF; 不是必需的。这里的演员也不是:text[i++]=(char)c;。您也不需要两个变量lastSize 和firstSize。您还应该检查realloc 的返回值。

【讨论】:

  • 我需要为初始数组分配第一个大小。没有分配,我无法将变量分配给数组。
  • @CursedChico 是的。你只需要一个变量。为什么是两个?删除lastSize 并将lastSize = i+firstSize; 更改为firstSize = i+firstSize; 或firstSize = firstSize*2;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 2020-09-26
相关资源
最近更新 更多