[問題] 關於getchar()的用法

看板C_and_CPP (C/C++)作者 (天飛)時間14年前 (2011/11/12 21:25), 編輯推噓2(203)
留言5則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Dev-C++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): getchar()的用法不如預期 餵入的資料(Input): 123456 預期的正確結果(Expected Output): 123456 錯誤結果(Wrong Output): 使用while loop => 246 do-while => 135 程式碼(Code):(請善用置底文網頁, 記得排版) int i=0; char a[100]={0}; while(getchar()!='\n') { a[i]=getchar(); i++; } printf("%s", a); 補充說明(Supplement): 想用getchar()把輸入的字元存到陣列裡,然後印出字串 但結果都會跳一格且只有一半 是否我的想法、用法有誤? 懇請大家幫我釐清觀念,謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.64.145.131

11/12 21:28, , 1F

11/12 21:29, , 2F
你while(getchar())也會吃掉一個字元
11/12 21:29, 2F

11/12 21:30, , 3F
感謝2F,恍然大悟阿!
11/12 21:30, 3F

11/12 21:31, , 4F
也感謝1F大大
11/12 21:31, 4F

11/12 21:32, , 5F
while((a[i]=getchar())!='\n') ++i;
11/12 21:32, 5F
文章代碼(AID): #1EldEnUQ (C_and_CPP)
文章代碼(AID): #1EldEnUQ (C_and_CPP)