[问题] 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