scanf( "%s", &array )

This is a discussion on scanf( "%s", &array ) within the C Programming forums, part of the General Programming Boards category; hey, Im led to believe that this is wrong. It even seems alittle to vauge to me... But how am ...

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    33

    scanf( "%s", &array )

    hey,

    Im led to believe that this is wrong. It even seems alittle to vauge to me...
    But how am i supposed recieve user input using
    Code:
     scanf("%5c", &array);
    or
    Code:
     scanf("%100c", &array)
    when i dont know how large the input will be...?

    Could i possibly use a MAX number for the input. Then fill in the unused characters with a '0' or '\0' ?

    ( btw, Im a novice C++ programmer, trying out C code. Me likey-likey. )

  2. #2
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    array should be an char array, so you do not need &
    you cannot read input without knowing the maximum size - you need to allocate array beforhead
    the width specified - will enssure that the array is not overwritten, if user presses more characters than could fit into array - the rest will be left in the input buffer till the next read operation

    Code:
    char array[100];
    if(scanf("%99s",array) ==1)
    {
       /* word is read */
    }
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  3. #3
    Registered User
    Join Date
    Aug 2008
    Posts
    33
    ...ok.

    So what about when you specify more input than the user enters?


    Im sure last time i tried this, the program wouldnt move on from this point untill all of the allocated space is used.
    Last edited by Else; 09-14-2008 at 02:45 PM.

  4. #4
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    you mean - what if the user enters the word longer than your buffer

    you can for example use fgetc to check what is the next character left by the scanf in the input buffer - if it some space - you have read the whole word, if it is not - input was too long - you can notify user, clear the input buffer and try again
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by Else View Post
    ...ok.

    So what about when you specify more input than the user enters?


    Im sure last time i tried this, the program wouldnt move on from this point untill all of the allocated space is used.
    You may be sure, but it didn't happen. %<number>s will read until number characters or until a space/enter key, but will then stop.

  6. #6
    Registered User
    Join Date
    Aug 2008
    Posts
    33
    no.
    What if your buffer is longer than their word....

    or do i deserve a slap for being stupid?

  7. #7
    Registered User
    Join Date
    Aug 2008
    Posts
    33
    Quote Originally Posted by vart View Post
    you mean - what if the user enters the word longer than your buffer

    you can for example use fgetc to check what is the next character left by the scanf in the input buffer - if it some space - you have read the whole word, if it is not - input was too long - you can notify user, clear the input buffer and try again
    I see.
    So i can increase the size of the buffer untill a whitespace is encountered then?

  8. #8
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    if your buffer is longer than their word
    the rest of the buffer goes unused
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  9. #9
    Registered User
    Join Date
    Aug 2008
    Posts
    33
    so its true.

    I do deserve a slap

  10. #10
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    So i can increase the size of the buffer untill a whitespace is encountered then?
    if you want to fit any word - you can go with dinamically increasing buffer - but better use fgetc to read input char by char, instead of scanf.

    In this case you can copy read characters into buffer, when you get to the buffer limit without encountering the whitespace - you will realloc it with bigger space...
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  11. #11
    Registered User
    Join Date
    Aug 2008
    Posts
    33
    cheers.

    I'll look into 'fgetc'.

  12. #12
    Registered User
    Join Date
    Aug 2008
    Posts
    33
    ...oh....

    I have just tried this :

    Code:
      int main()
      {
        char   array[30];
    
        printf("\n\n ENTER YOUR NAME: ");
        scanf("&#37;30c", array );
        printf("\n\n");
    
        return 0;
      }
    and now my program wont move forth from the user input phase...

    Im not using "%s" , I think it makes it look cheap. Or am I being inpractical/un-professional...
    (not that I am anyway).
    Last edited by Else; 09-14-2008 at 03:02 PM.

  13. #13
    Registered User
    Join Date
    Apr 2008
    Posts
    40
    Hi!

    I usually do it as follows. It might look a bit complicated, but I works for me:

    Code:
    char* tmp=(char *)malloc(50*sizeof(char)); // Room for 50 chars. Set to what you want, one 
                                                                         // space extra needed for null-termination. 
    int x=0;
    char ch;
    printf("\nEnter your name: ");
    ch=getc(stdin);
    while((ch!=10)&&(x<254))
    {
        tmp[x]=ch;
        x++;
        ch=getc(stdin);
    }
    tmp[x]=0; // null-termination...
    And then you just create a new buffer the size of x+1 and copy from tmp to the new buffer with
    "for(newx=0;newx<=x;x++)"

  14. #14
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    983
    A couple of observations:
    Code:
    char* tmp=(char *)malloc(50*sizeof(char));
    No need to cast malloc() in C, and sizeof(char) is always 1. Not errors, but superfluous.
    Code:
    char ch;
    ch=getc(stdin);
    while((ch!=10)&&(x<254))
    getc() returns an int, and so ch should be declared as such. This is so that you can properly check for end of file (which is detectable when getc() returns EOF). In addition, it's not a good idea to use magic numbers as was done with the 10 in the above code. Presumably this is a check for a newline: in that case, use '\n'. It's clearer and doesn't care about what the character set looks like. A nice simple loop for reading characters up to EOF or a newline can look like:
    Code:
    int c;
    while( (c = getchar()) != EOF && c != '\n') ;
    Note that the proposed code is quite similar to the standard function fgets(), which I'd recommend for reading lines instead of doing something by hand:
    Code:
    char line[1024];
    while(fgets(line, sizeof line, stdin) != NULL)
    {
      /* do something with line */
    }
    There are still annoyances (what happens with a line > 1023 characters, for example), but that's life with C.

  15. #15
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Quote Originally Posted by cas View Post
    Code:
    char line[1024];
    while(fgets(line, sizeof line, stdin) != NULL)
    {
      /* do something with line */
    }
    There are still annoyances (what happens with a line > 1023 characters, for example), but that's life with C.
    Why? fgets() will read 1023 characters, put a null character at the end and that's it. A line is terminated by a \n character, so you can just check if the 1023 element of line is \n. If it is then it means you read a whole line. If not then you didn't. So you can just fgets() again.

    You can actually have a code like:
    Code:
    int size=1;
    char *name = malloc(size);
    while((ch = getch()) != \n) {
       name = realloc(name, size++);
       //Some code that puts the ch into name
    }
    which will allocate memory for each character, but is kind of inefficient. Or:
    Code:
    int inputSize = 0;
    char *name = malloc(SIZE);
    //Some code that reads input until \n. For every character read it will increase inputSize
    name = realloc(name, inputSize+1)
    which will be as before but in the end you will have the desired size for name. This should be a more efficient code, since you call realloc once.

    In C++ you have a string class that makes your life easier. But you can simulate the variable size of string with one of the above codes.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 07:35 AM
  2. Replies: 2
    Last Post: 02-20-2005, 12:48 PM
  3. scanf issue
    By fkheng in forum C Programming
    Replies: 6
    Last Post: 06-20-2003, 07:28 AM
  4. Scanf and integer...
    By penny in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 06:36 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21