[英]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
,但這沒有幫助。
這是因為標准輸出流stdout
是行緩沖的。 這意味着直到輸出換行符'\\n'
或刷新緩沖區后緩沖區已滿,屏幕上才會顯示輸出。 另外,您不應該轉換malloc
或realloc
的結果。 您還應該檢查malloc
或calloc
的結果是否為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.