code.club

 找回密碼
 立即註冊
搜索
查看: 6603|回復: 1
打印 上一主題 下一主題

為何輸出後會少掉最前面的字元?

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2014-12-19 18:54:49 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
本帖最後由 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.
回復

使用道具 舉報

沙發
 樓主| 發表於 2014-12-19 19:16:24 | 只看該作者
#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'出了問題?
回復 支持 反對

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|手機版|Archiver|code.club  

GMT+8, 2024-4-25 05:07 , Processed in 0.087769 second(s), 16 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表