【问题标题】:Inputting individual characters in C在 C 中输入单个字符
【发布时间】:2014-03-23 08:15:46
【问题描述】:

我有这段代码,我希望从用户那里读取一个单个字符,然后重新打印它,然后重新分配新内存以存储用户将输入的下一个字符;所有这些重复,直到用户输入“1”字符。但是,在用户按下“return”之前,我的程序什么都不做,然后回显整个字符串。为什么会这样?

#include <stdlib.h>
#include<stdio.h>

int main()
{
    char *s = (char *)malloc(sizeof(char));
    int i = 1 ;
    do
    {
        scanf(" %c",s+i-1);
        printf("%c" , *(s+i-1));
        i++ ;
        s = (char *)realloc(s , sizeof(char)*i);
    }while(*(s+i-1) != '1');
    printf("\n\n %s" , s);
    return 0;
}

这是我所期望的:

h // input from user
h // the output
w // input from user
w // output from user

但这就是我得到的:

what // input from user
what // output 

我尝试将scanf 替换为getchar,但这无济于事。

【问题讨论】:

  • 1.你为什么在malloc 上使用演员表? 2. 首先 malloc 合理的数量(比如 2Ks)并避免重新分配。
  • 在哪个操作系统上?
  • stdin 缓冲字符,直到用户按下 enter 键。然后它立即将整行提供给您的程序。这允许用户在提交之前编辑该行。如果您一次需要一个字符,则必须更改终端设置。
  • 看来你要使用GNU readline
  • @Learner - 这取决于操作系统。 malloc 将从操作系统获得一大块内存,并且该大小将取决于操作系统以使其舒适。 realloc 可能会咬入该内存或要求 malloc 从更大的块中再次询问。因此,请 malloc 为您手头的任务提供合理的内存量并节省函数调用

标签: c malloc scanf getchar


【解决方案1】:

输入被缓冲并且在用户点击返回之前不会被传递到您的程序。请参阅this questionthis question

您对malloc/realloc的使用与此无关。

【讨论】:

  • 此外,stdout 也被缓冲了。
  • 首先,感谢编辑,其次,我第一次尝试输入大约50个字符,它重新打印! ,请注意,我只分配了 1 个字节!这是怎么回事?
【解决方案2】:

stdin 缓冲字符直到用户按下回车键,所以它不会处理单个字符。

【讨论】:

    【解决方案3】:

    这是因为标准输出流stdout 是行缓冲的。这意味着在输出换行符'\n' 或缓冲区已满(刷新缓冲区时)之前,输出不会出现在屏幕上。此外,您不应该转换mallocrealloc 的结果。您还应该检查malloccalloc 的结果NULL

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void) {
        char *s = malloc(sizeof *s);
        if(s == NULL) {
            printf("not enough memory to allocate\n");
            return 1;
        }
        int i = 0;
        char *temp;
        do {
            scanf("%c", s + i);
            printf("%c\n", *(s + i));
            i++;
            temp = s;
            s = realloc(s, i * sizeof *s);
            if(s == NULL) {
                printf("not enough memory to allocate\n");
                s = temp;
                // handle it
                // break;
            }
        } while(*(s + i) != '1');
        printf("%s\n", s);
    
        // after you are done with s, free it
        free(s);
    
        return 0;
    }
    

    【讨论】:

    • 你说“你不应该转换 malloc 或 realloc 的结果”,你能告诉我为什么吗?
    • @Learner 那是因为没有任何好处,如果您忘记包含标题 stdlib.h 可能会导致错误。阅读本文了解详情stackoverflow.com/questions/605845/…
    猜你喜欢
    • 2010-10-08
    • 1970-01-01
    • 2010-09-23
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    相关资源
    最近更新 更多