[問題] scanf overflow/空值

看板C_and_CPP (C/C++)作者 (宅熊冗厚)時間11年前 (2014/10/21 23:05), 編輯推噓0(003)
留言3則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) GCC 問題(Question): 1.允許輸入空值(只按enter則不存值) 2.輸入字串過長時,忽略過長部分的字元 餵入的資料(Input): (\n) 0123456abcdefg(\n) q(\n) 預期的正確結果(Expected Output): is saved. 0123456 is saved. 錯誤結果(Wrong Output): 0123456 is saved. abcdefg is saved. 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> #include <stdlib.h> #include <string.h> #define data_size 8 void main(){ char a[data_size]; char format[10]; sprintf(format, "%%%is", (data_size-1)); while(1){ scanf(format, a); if(strcmp(a, "q") == 0) break; printf("%s is saved.\n", a); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.42.215.218 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1413903948.A.400.html

10/22 01:33, , 1F
加入判別條件:過長的時候要吃到\n才會開始繼續儲存
10/22 01:33, 1F

10/22 01:34, , 2F
然後你餵入的q(\n)這行是...?
10/22 01:34, 2F

10/25 00:56, , 3F
終止那個loop
10/25 00:56, 3F
文章代碼(AID): #1KHdPCG0 (C_and_CPP)
文章代碼(AID): #1KHdPCG0 (C_and_CPP)