Thread: Is this the correct way...

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    21

    Is this the correct way...

    to get a user array of string input?

    Code:
    printf("Title: ");
    scanf("%[^\n]", title);
    while(fgetc(stdin)!='\n');
    if no, can you advise what are the ways to get an array of string, eg. "C rulez big time" coz I've been getting funny result with the method above.

  2. #2
    root
    Join Date
    Sep 2003
    Posts
    232
    Nope, using scanf for string input is unsafe, when you manage to do it safely it's just an ugly kludge. Try this instead:
    Code:
    printf("Title: ");
    fflush(stdout);
    if (fgets(title, sizeof title, stdin) != NULL) {
            /* Use title */
    } else {
            /* fgets failed */
    }
    The information given in this message is known to work on FreeBSD 4.8 STABLE.
    *The above statement is false if I was too lazy to test it.*
    Please take note that I am not a technical writer, nor do I care to become one.
    If someone finds a mistake, gleaming error or typo, do me a favor...bite me.
    Don't assume that I'm ever entirely serious or entirely joking.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linux for GNU/Linux is not correct?
    By password636 in forum Linux Programming
    Replies: 8
    Last Post: 03-31-2009, 08:30 PM
  2. Is this correct : passing strings?
    By socket in forum C Programming
    Replies: 15
    Last Post: 11-25-2008, 02:03 PM
  3. correct order to insert new node?
    By campermama in forum C++ Programming
    Replies: 1
    Last Post: 06-16-2004, 07:51 PM
  4. Replies: 1
    Last Post: 05-26-2004, 12:58 AM
  5. Loop until enter correct value
    By jchanwh in forum C Programming
    Replies: 2
    Last Post: 11-27-2001, 01:23 AM