為何輸出後會少掉最前面的字元?
本帖最後由 enter 於 2014-12-19 19:03 編輯根據書上,下面有二個程式寫法雖有點差異,但輸出結果應相同。可是有一個的輸出結果,竟然是第一個輸入的字元不見了?
就是在一個有100個元素的字元陣列(字串)中隨意輸入字元,直到按下enter為止,然後再印出剛輸入的所有字元:
第一種寫法輸出很正常。
#include <stdio.h>
#include <conio.h>
int main(void){
char x;
int y;
printf("enter letters:\n");
for(y=0;y<100;y++)
{
x=getche();
if(x=='\r') break;
}
for(y=0;x!='\r';y++)
printf("%c ",x);
return 0;
}
第二種寫法,輸出時的第一個字元不見了?
#include <stdio.h>
#include <conio.h>
int main(void){
char x;
int y;
printf("enter letters:\n");
for(y=0;y<100;y++)
{
x=getche();
if(x=='\r') break;
}
for(y=0;x;y++)
printf("%c ",x);
return 0;
}
差別在於紅字部份,請問第二個的錯誤在哪裡?
thanks. #include <stdio.h>
#include <conio.h>
int main(void){
char x;
int y;
printf("enter a string:\n");
gets(x);
printf(x);
printf("\n");
puts(x);
for(y=0;x;y++)
printf("%c",x);
printf("\n");
for(y=0;x!='\r';y++)
printf("%c",x);
return 0;
}
上面這一道將數種寫法都放在一起,反而最後那種寫法x!='\r'出了問題?
頁:
[1]