我有一個循環問題,並且fgets
和sscanf
以獲得輸入。C fgets和sscanf在循環中:防止無用的循環
我知道的問題是從輸入的malloc的大小。如果用戶輸入的號碼大於malloc我想再次要求輸入一個新號碼。 但是在這段代碼中,如果用戶輸入的數字太大,我認爲它會循環很多時間(字/ 8的大小)。
如何再次詢問用戶輸入新號碼,例如4次循環。 看到我用大號製作的例子。
這個想法是在循環後釋放輸入,但它不起作用。有任何想法嗎 ?
有我的代碼:
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
int main(void) {
char x[8];
char y[8];
int result = 0;
char *input=malloc(sizeof(char)*8);
bool answer = 0;
char *pos;
while(!answer) {
fgets(input, sizeof(input)-1, stdin);
//remove the /n from fgets
if ((pos=strchr(input, '\n')) != NULL)
*pos = '\0';
result = sscanf (input, "%s %s", x, y);
printf("%d\n", result);
if(result < 2) {
fprintf(stderr, "There is an error with the number you give, try again\n");
} else {
printf("%s\n", x);
printf("%s\n", y);
}
}
return 0;
}
和輸出爲: 「01 01」
01 01
2
01
01
輸出爲:000000005 000000005
0000000000005 000000000000005
1
There is an error with the number you give, try again
1
There is an error with the number you give, try again
2
5
0000
1
There is an error with the number you give, try again
1
There is an error with the number you give, try again
'的sizeof(輸入)整體更換,如果()'是指針的大小,而不是malloc的內存。你很幸運,這兩個數字都是8的好機會。 – mch 2014-09-25 09:22:53
假設你修改了你的輸入緩衝區來動態增加消耗你的行內容,你會發現一個全新的問題,試圖像''sscanf''這樣的字符串。 0000000000005「'變成'char [8]',對嗎?我的意思是,你試圖把14個字符放到一個只能容納8個字符的緩衝區中,當你使用它時,'sscanf'是幸福地不知道這個限制的。 – WhozCraig 2014-09-25 09:32:37