英文:
sscanf parsing issue with numeric input - returning unexpected results
问题
我尝试使用sscanf
将字符串解析为数字,但解析不正确。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#define NUMBER_OF_LINES_BUFFER sizeof(int)
int main()
{
...
...
// 获取行数
char number[NUMBER_OF_LINES_BUFFER];
int number_of_lines = 0;
while (number_of_lines < 1)
{
print_message("输入行数。然后按回车\n");
fgets(number, NUMBER_OF_LINES_BUFFER, stdin);
if (sscanf(number, "%d", &number_of_lines) == true)
{
printf("行数: %d\n", number_of_lines);
if (number_of_lines < 1)
{
print_message("错误: 应为正整数。\n");
}
}
}
...
...
}
它应该将"0012\n"
解析为12
,但实际上解析为1
。
英文:
I'm trying to parse a string to number using sscanf
but it does not parse correctly.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#define NUMBER_OF_LINES_BUFFER sizeof(int)
int main()
{
...
...
// get number of lines
char number[NUMBER_OF_LINES_BUFFER];
int number_of_lines = 0;
while (number_of_lines < 1)
{
print_message("Enter number of lines. Then enter\n");
fgets(number, NUMBER_OF_LINES_BUFFER, stdin);
if (sscanf(number, "%d", &number_of_lines) == true)
{
printf("number_of_lines: %d\n", number_of_lines);
if (number_of_lines < 1)
{
print_message("ERROR: should be a positive integer.\n");
}
}
}
...
...
}
It should parse "0012\n"
to 12
. But instead parses it to 1
.
答案1
得分: 1
sizeof(int)
在您的平台上为 4。因此,您声明 char number[4];
。这有3个字符和空终止符的空间。当您输入 0012
时,它只读取 001
。
使它更大。
#define NUMBER_OF_LINES_BUFFER 10
英文:
sizeof(int)
is 4 on your platform. So you're declaring char number[4];
. This has room for 3 characters and the null terminator. When you enter 0012
, it's only reading 001
.
Make it bigger.
#define NUMBER_OF_LINES_BUFFER 10
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论