[問題] while裡跑printf會把字串覆蓋掉

看板C_and_CPP (C/C++)作者 (白毛)時間16年前 (2009/06/15 01:15), 編輯推噓1(106)
留言7則, 3人參與, 最新討論串1/1
#include<stdio.h> #include<string.h> int main() { char input[80]={'\0'},origin[80]={'\0'},tmp[80]={'\0'}; char *token; while(fgets(input,80,stdin)) { strcpy(origin,input); strtok(origin,"\n"); token=strtok(input," "); token=strtok(NULL," \n"); if(strncmp("RSUB",token,4)==0) strcpy(tmp," 4C0000"); printf("%s%s\n",origin,tmp); } return 0; } ================================================ 我用a.out<fin.txt的方式輸入 fin.txt的內容如下 ================================================ 1000 RSUB 1000 RSUB 1000 RSUB 1000 RSUB ================================================ 我預期的結果應該是 1000 RSUB 4C0000 1000 RSUB 4C0000 1000 RSUB 4C0000 1000 RSUB 4C0000 ================================================ 可是跑出來的結果卻是 4C0000UB 4C0000UB 4C0000UB 4C0000UB (每一行前面的1000 RS都被4C0000覆蓋掉了) 我用a.out<fin.txt來輸入就會出現這個問題 可是如果我用複製貼上來輸入就不會有這個問題 為什麼會這樣啊 我找不出哪裡有問題 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.119.135.80

06/15 09:24, , 1F
因為 origin 中為 "1000 RSUB\r\n" 你只把 \n 拿掉。
06/15 09:24, 1F

06/15 16:19, , 2F
請問\r是…?
06/15 16:19, 2F

06/15 16:29, , 3F
為何會出現\r呢
06/15 16:29, 3F

06/15 18:14, , 4F
Windows系統的換行就是\r\n, 分別表示return與new line
06/15 18:14, 4F

06/15 18:15, , 5F
\n\r還是\r\n啊!?記不清楚了, 總之就是txt的換行在MSwin
06/15 18:15, 5F

06/15 18:16, , 6F
下就是用了這兩個byte來完成; \r會列頭, \n下移新行;
06/15 18:16, 6F

06/15 18:16, , 7F
印像中大概就是這樣; 不過print的時候\n就行了....
06/15 18:16, 7F
文章代碼(AID): #1ADJ0mk- (C_and_CPP)
文章代碼(AID): #1ADJ0mk- (C_and_CPP)