[sprintf] Wrong handling of "+ " flags

Open Beginner friendly
#16 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
62/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
c
Domain
backend

Research direction

The bug is in stbsp__lead_sign() in stb_sprintf.h, around lines 294-307, which checks the negative, space and plus flags in the wrong order. Read that function, then compare its output with a standard printf for the eight %+ 10i, % +10f, %+ 10g and %+ 10a cases in the issue. Done when the plus flag takes precedence over the space flag in every case and the output matches the standard.

Written by the indexing model from the issue text.

Description

The standard says:

If the space and + flags both appear, the space flag is ignored.

STB vs standard-conforming:

printf("%+ 10i", 1);   // "         1" vs "        +1"
printf("% +10i", 1);   // "         1" vs "        +1"
printf("%+ 10f", 1.0); // "  1.000000" vs " +1.000000"
printf("% +10f", 1.0); // "  1.000000" vs " +1.000000"
printf("%+ 10g", 1.0); // "         1" vs "        +1"
printf("% +10g", 1.0); // "         1" vs "        +1"
printf("%+ 10a", 1.0); // "       0x1.000000p+0" vs "      +0x1.000000p+0"
printf("% +10a", 1.0); // "       0x1.000000p+0" vs "      +0x1.000000p+0"

Fix: the stbsp__lead_sign() function should change the order of its checks: first negative, then plus, then space (now it checks negative, space, plus):
https://github.com/nothings/stb/blob/f0569113c93ad095470c54bf34a17b36646bbbb5/stb_sprintf.h#L294-L307

Dominant language
C
Stars
18
Forks
5
Avg merge
1m
Merged PRs (30d)
3

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from nothings/stb_sprintf

All issues in nothings/stb_sprintf

Similar issues

More C issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.