LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Is it safe to use scanf for anything?? (https://www.linuxquestions.org/questions/programming-9/is-it-safe-to-use-scanf-for-anything-24951/)

purpleburple 07-03-2002 11:12 AM

Is it safe to use scanf for anything??
 
I read in a few books before that scanf wasn't such a good choice in input readers. Is there a situation where one would prefer to use scanf?

Up until now since I'm fairly new to C I've been using it for the bulk of input.

thank you :confused:

Mara 07-03-2002 12:39 PM

Rather not. Scanf is good if you're 100% sure that the imput will be exactly what you want. Of course, you never are. Even when you ask an user to enter 'y' or 'n' (char), you can get '7' or "aaaa". So scanf is not a good choce.

BTW It looks it's my 1000th post... There's someone who asked me to be mentioned there. Yes, so he is ;)

biosx 07-03-2002 01:06 PM

Yeah, I choose not to use scanf() in most of my programs. Instead I use the fgets() function and read from stdin like so:

Code:

#include <stdio.h>

int main(void)
{
    char string[80];

    printf("Enter a string: ");
    fgets(string, sizeof(string), stdin);

    printf("\n\nYou entered: %s");
 
    return 0;
}

The only problem with fgets() is that it captures the newline and includes it into your string. However, getting rid of that newline is simple. Good luck!

purpleburple 07-03-2002 02:19 PM

thanks brothers and sisters!

Mara 07-03-2002 03:18 PM

After you have a line (using fgets or your own function) you need ito conver it to the format you'd like to have. It means reading char by char and checking everything correct. It's boring. In my opinion it's the worst part of a program.

purpleburple 07-03-2002 06:19 PM

thnks Mara! :)


All times are GMT -5. The time now is 12:15 PM.