[問題] scanf overflow/空值

作者: lionheart60 (宅熊冗厚)   2014-10-21 23:05:43
開發平台(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);
}
}
作者: s89227 (Kei)   2014-10-22 01:33:00
加入判別條件:過長的時候要吃到\n才會開始繼續儲存然後你餵入的q(\n)這行是...?
作者: lionheart60 (宅熊冗厚)   2014-10-25 00:56:00
終止那個loop

Links booklink

Contact Us: admin [ a t ] ucptt.com