raz789
raz789

Reputation: 19

Reading with scanf without delimits

Sample input from user:

A10

Trying to read in this input

scanf_s("%c%d", &playerX, &playerY, 10);

Does input from the user need to be delimited? Is it possible to read in like this?

Edit: I have tested this and it just crashes.

Edit 2: Solution: scanf_s("%c%d", &playerX, 1, &playerY);

Upvotes: 0

Views: 90

Answers (1)

chqrlie
chqrlie

Reputation: 144585

The solution using scanf_s is tricky:

char playerX;
int playerY;

if (scanf_s("%c%d", &playerX, (size_t)1, &playerY) == 2) {
    /* input parsed correctly */
    /* input stopped after the last digit in playerY */
    /* You cannot limit the number of digits this way */
} else {
    /* end of file or missing number */
    /* input stopped before the offending character */
}

scanf_s is a poor fix for scanf's very many shortcomings. The array size must be passed after each pointer argument for c, s and [ formats. But this size must be passed as an rsize_t, which is the same as a size_t with a restriction on the maximum value. Passing 1 is plain wrong as 1 is an int and scanf_s takes a variable number of arguments, thus does not convert extra arguments automatically. If will fail in mysterious ways on architectures where int and size_t differ in size, such as 64 bit windows, linux and OS/X.

You can avoid subtle problems like this by increasing the warning level of the compiler. gcc -Wall -Werror or clang -Wall -Werror are a good start. Never ignore these helpful warnings, if you don't understand them, you probably do not know what your code really does.

Unless scanf_s is mandated by your coding rules or your compiler, it is simpler to use scanf and just as safe for this format:

if (scanf("%c%d", &playerX, &playerY) == 2) ...

Upvotes: 1

Related Questions