Monday 2 September 2013

A Few Things About The Scanf Function.

Programming With C by Byron S. Gottfried is a wonderful book. I was avoiding this book because it felt too formal, and it just seemed so outdated....with stuff like "A 256kb micro computer(Also Called Personal Computer) is commonly....". I also hadn't gotten over the feeling that I would not understand the material presented. But when I started reading it it is really good. I can understand most of it now since I believe my introduction to C phase is complete.
Leafing through it, I believe I also spied an example file compress program near the end, though I'm not sure if that is what it is.
Because this book is written as a textbook, it packs a lot more information in fewer pages. Here are some of the interesting things I learnt about scanf().

Consider this program:

#include <stdio.h>

main()
{
    char str1[50];

    printf("Enter a string of ONLY NUMBERS: ");
    scanf("%[ 1234567890]",str1);

    printf("%s",str1);
}

This program will prompt you to enter numbers. As long as you enter numbers, all is well and it is faithfully saved in the string variable str1, but as soon as you enter something other than a number, scanf stops reading your input and assigns whatever numbers you may have entered to str1.
This is because the characters within the [] are the only ones accepted. There is also a space in there so you can enter something like "192 168 1 1" and it will get assigned and displayed.

But if you enter "156 A132 M56", only 156[space] will be assigned to str1.
I don't see any reason why we would use this, but we never know.

scanf does not recognize spaces by default. Say:

#include <stdio.h>

main()
{
    char str1[50];

    printf("Enter a string: ");
    scanf("%s",str1);

    printf("%s",str1);
}

Would run like this:

Although I entered "Sagacious Tien", it only accepted Sagacious and when it saw the white space, it ended it's read.
The obvious and, I suppose, better way to have the full name assigned to str1 is to use gets(str1), but we can also do:

#include <stdio.h>

main()
{
    char str1[50];

    printf("Enter a string: ");
    scanf("%[^\n]",str1);

    printf("%s",str1);
}

the[^\n] tells scanf to not stop reading until it encounters the enter key (represented in C by '\n').

#include <stdio.h>

main()
{
    char str1[50];

    printf("Enter a string: ");
    scanf("%5s",str1);

    printf("%s",str1);
}

This tells scanf to only read 5 characters and ignore the rest. If you enter "1234567890............", str1 will be assigned "12345" and the rest of the input is ignored. Bounds Checking of sorts.




No comments:

Post a Comment