Reza Sy
Reza Sy

Reputation: 7

Extract part of an input string by scanf()

I ask my question by these two examples, in the first program when I enter my name it works correctly:

#include <stdio.h>

int main ()
{
    char str [20];

    while(1)
    {
       printf ("Enter your name: ");
       scanf ("%19s",str);
       printf ("Your name is %s\n",str);
    }
    return 0;
}

Output:

Enter your name: Reza
Your name is Reza
Enter your name: 

But in the following program the result is not as expected:

#include <stdio.h>

int main ()
{
    char str [20];

    while(1)
    {
        printf ("Enter your name: ");
        scanf ("name=%19s",str);
        printf ("Your name is %s\n",str);
    }
    return 0;
}

When entering name=Reza as the input, the program repeatedly print the output:

Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
...

In your opinion what's the mistake? Thank in advance

Upvotes: 0

Views: 412

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84652

It is explained by a simple reference to man scanf. In your first case:

scanf ("%19s",str);

The %s conversion specifier ignores leading whitespace so the '\n' left in the input buffer (stdin) is silently consumed.

In your second case:

scanf ("name=%19s",str);

You format string is looking for a literal "name=" as part of the input, which since the '\n' left after your prior input isn't consumed, a matching failure occurs because your input is actually "\nname=...", character extraction ceases at that point leaving a characters in the input buffer unread -- leading to the same failure on every subsequent input.

You can solve the problem including an empty space at the beginning of your format string causing any leading whitespace to be consumed with:

scanf (" name=%19s",str);

Now you can input, for example:

name=Gary
name=Tom
...

(of course you will still have an extraneous character problem if the user enters more than 19-characters for any name -- or if a cat accidentally steps on the keyboard)

You must also check the return of EVERY input function used -- especially scanf. Simply check that the number of expected conversions takes place, e.g.

if (scanf (" name=%19s",str) != 1) {
    fputs ("error: conversion failed.\n", stderr);
    /* handle error */
}

Upvotes: 2

Related Questions