簡體   English   中英

在C中輸入單個字符

[英]Inputting individual characters in C

我有這樣的代碼,這是我從希望讀取用戶的單個字符,然后再打印出來,然后realloc'ing新的內存來存儲下一個字符該用戶將進入; 所有這些重復直到用戶輸入“ 1”字符為止。 但是,我的程序在用戶按下“返回”鍵之前不執行任何操作,然后回顯整個字符串。 為什么會這樣呢?

#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 

我試圖用getchar代替scanf ,但這沒有幫助。

輸入被緩沖,直到用戶按下回車鍵,才將其傳遞給您的程序。 看到這個問題這個問題

您對malloc / realloc使用與此無關。

這是因為標准輸出流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;
}

stdin會緩沖字符,直到用戶按下Enter鍵為止,這樣就不會處理單個字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM