Last active
September 29, 2016 06:25
-
-
Save dtoma/c8489c36ff6cd6caa61f50e2980da5ac to your computer and use it in GitHub Desktop.
safer sscanf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
template <typename ... Args> | |
bool safe_sscanf(char const* s, char const* fmt, Args*... args) | |
{ | |
constexpr auto len = sizeof...(args); | |
auto n = sscanf(s, fmt, args...); | |
if (n != len) | |
{ | |
printf("sscanf error: captured %d instead of %zu - string was [%s], format was [%s]\n", n, len, s, fmt); | |
return false; | |
} | |
return true; | |
} | |
int main() | |
{ | |
int a = 0, b = 0, c = 0; | |
if (!safe_sscanf("23:59:59", "%2u:%2u:%2u", &a, &b, &c)) | |
{ | |
// If we'd passed "23:59::59" as input, we'd have gotten an error: | |
// > sscanf error: captured 2 instead of 3 - string was [23:59::59], format was [%2u:%2u:%2u] | |
return 1; | |
} | |
// This would still give us an unwanted result if the input was, for example, "2:3:59:59": we'd get [2, 3, 59], | |
// because %2 means "up to 2", not "exactly 2". | |
// For input validation, regexes are more powerful. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gcc7 -O3 -Wall -Wextra -pedantic -Wformat -std=c++11