[英]printf creates no or wrong output
我編寫了一個程序,出於調試目的,我想在控制台中編寫一些文本。 現在,我發現了一個非常奇怪的錯誤,找不到解決方案。 這是我的代碼:
int main(void)
{
setvbuf (stdout, NULL, _IONBF, 0);
char input[50];
char check = 'a';
for(int i=0; check != EOF; ++i){
check = scanf("%s", input);
printf("%s\n",input);
}
fflush(stdout);
char* myAnswer = createList();
printf("%s\n", myAnswer);
return 0;
}
//-----------------------------------------------------------------------------
char* createList(){
char* msg = malloc(6*sizeof(char));
msg[0]='A';
msg[1]='B';
msg[2]='C';
msg[3]='D';
msg[4]='E';
msg[5]='\0';
return msg;
}
for循環可以正常工作,但是永遠不會編寫“ ABCDE”。 相反,有時我在輸入中保存的最后一個單詞第二次在控制台中寫入,但缺少最后一個字母。 或根本什么都沒有寫。 我試圖通過刷新緩沖區或將其設置為零大小來解決它。 但是沒有任何幫助。 我與Qt Creator一起工作,該錯誤是否出在我的IDE中?
更正了代碼的某些部分(例如中斷EOF循環,將數據類型更改為int等)。 請查看以下代碼是否有效。 您需要在最后一個輸入之后按Ctrl-D,以確保循環中斷。
#include <stdio.h>
#include <stdlib.h>
char* createList();
int main(void)
{
setvbuf (stdout, NULL, _IONBF, 0);
char input[50];
for(;;){
if (fgets(input, 50, stdin) == NULL)
break;
printf("%s\n",input);
}
fflush(stdout);
char* myAnswer = createList();
printf("%s\n", myAnswer);
return 0;
}
//-----------------------------------------------------------------------------
char* createList(){
char* msg = (char *) malloc(6*sizeof(char));
msg[0]='A';
msg[1]='B';
msg[2]='C';
msg[3]='D';
msg[4]='E';
msg[5]='\0';
return msg;
}
以下代碼
1) eliminates the code clutter
2) checks for errors
3) compiles cleanly
4) when user input <CTRL-D> (linux) then program receives a EOF
#include <stdio.h>
#include <stdlib.h>
#define MAX_INPUT_LEN (50)
char *createList(void);
int main(void)
{
char input[MAX_INPUT_LEN];
while( 1 == scanf("%49s", input) )
{
printf("%s\n",input);
}
char* myAnswer = createList();
printf("%s\n", myAnswer);
return 0;
}
//-----------------------------------------------------------------------------
char* createList(){
char* msg = malloc(6);
if( NULL == msg )
{ // then malloc failed
perror( "malloc failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
msg[0]='A';
msg[1]='B';
msg[2]='C';
msg[3]='D';
msg[4]='E';
msg[5]='\0';
return msg;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.