code.club

標題: 為何輸出後會少掉最前面的字元? [打印本頁]

作者: enter    時間: 2014-12-19 18:54
標題: 為何輸出後會少掉最前面的字元?
本帖最後由 enter 於 2014-12-19 19:03 編輯

根據書上,下面有二個程式寫法雖有點差異,但輸出結果應相同。可是有一個的輸出結果,竟然是第一個輸入的字元不見了?

就是在一個有100個元素的字元陣列(字串)中隨意輸入字元,直到按下enter為止,然後再印出剛輸入的所有字元:
第一種寫法輸出很正常。
#include <stdio.h>
#include <conio.h>
int main(void){

char x[100];
int y;
printf("enter letters:\n");
for(y=0;y<100;y++)
{
x[y]=getche();
if(x[y]=='\r') break;
}

for(y=0;x[y]!='\r';y++)
printf("%c ",x[y]);

return 0;
}


第二種寫法,輸出時的第一個字元不見了?
#include <stdio.h>
#include <conio.h>
int main(void){

char x[100];
int y;
printf("enter letters:\n");
for(y=0;y<100;y++)
{
x[y]=getche();
if(x[y]=='\r') break;
}

for(y=0;x[y];y++)
printf("%c ",x[y]);

return 0;
}


差別在於紅字部份,請問第二個的錯誤在哪裡?

thanks.
作者: enter    時間: 2014-12-19 19:16
#include <stdio.h>
#include <conio.h>
int main(void){

char x[80];
int y;
printf("enter a string:\n");
gets(x);
printf(x);
printf("\n");
puts(x);
for(y=0;x[y];y++)
printf("%c",x[y]);
printf("\n");
for(y=0;x[y]!='\r';y++)
printf("%c",x[y]);
return 0;
}

上面這一道將數種寫法都放在一起,反而最後那種寫法x[y]!='\r'出了問題?




歡迎光臨 code.club (http://code.club/) Powered by Discuz! X3.2