sscanf解析数字输入时出现问题 – 返回意外结果

huangapple go评论125阅读模式
英文:

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");
      }
    }
  }
  ...
  ...
}

它应该将&quot;0012\n&quot;解析为12,但实际上解析为1

英文:

I'm trying to parse a string to number using sscanf but it does not parse correctly.

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;stdbool.h&gt;
#include &lt;ctype.h&gt;

#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 &lt; 1)
  {
    print_message(&quot;Enter number of lines. Then enter\n&quot;);
    fgets(number, NUMBER_OF_LINES_BUFFER, stdin);

    if (sscanf(number, &quot;%d&quot;, &amp;number_of_lines) == true)
    {
      printf(&quot;number_of_lines: %d\n&quot;, number_of_lines);
      if (number_of_lines &lt; 1)
      {
        print_message(&quot;ERROR: should be a positive integer.\n&quot;);
      }
    }
  }
  ...
  ...
}
  

It should parse &quot;0012\n&quot; 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

huangapple
  • 本文由 发表于 2023年4月11日 02:04:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定