【发布时间】:2014-09-25 09:17:11
【问题描述】:
我在循环和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(input)是指针的大小,而不是 malloc 内存的大小。你很幸运,两者都是 8 的机会很好。 -
假设您将
input缓冲区修复为动态增长以消耗您的行内容,您会意识到尝试将sscanf像"0000000000005"这样的字符串转换为char[8]时遇到了一个全新的问题,对?我的意思是,您正试图将 14 个字符推入一个只能容纳 8 个字符的缓冲区,而sscanf在您使用它时完全没有意识到这个限制。