Input buffer size question?!

This is a discussion on Input buffer size question?! within the C Programming forums, part of the General Programming Boards category; char buffer[80]; fgets(buffer,sizeof buffer,stdin); How can i make the buffer size the exact size of the input that will be ...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    35

    Input buffer size question?!

    char buffer[80];

    fgets(buffer,sizeof buffer,stdin);

    How can i make the buffer size the exact size of the input that will be entered in so if i enter lets say "hello" and the buffer will hold H,E,L,L,O,<garbage>, instead of having garbage right after hello and then the null terminator at 79? how can i make it so that the buffer just holds H,E,L,L,O,\n instead? or the exact size of any word entered in? so i can compare strings in the future

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,931
    Quote Originally Posted by shivam1992
    How can i make the buffer size the exact size of the input that will be entered in so if i enter lets say "hello" and the buffer will hold H,E,L,L,O,<garbage>, instead of having garbage right after hello and then the null terminator at 79? how can i make it so that the buffer just holds H,E,L,L,O,\n instead? or the exact size of any word entered in? so i can compare strings in the future
    In C, a string is a contiguous sequence of characters terminated by a null character. Therefore, "hello" would be stored as 'h', 'e', 'l', 'l', 'o', '\0', <garbage>. Thus, the <garbage> will be ignored when comparing strings since the comparison stops at the '\0'.

    That said, since you are using fgets, the newline character will also be stored (just before the null character), unless the input including the newline is 80 characters or more.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Buffer size question.
    By Swerve in forum C++ Programming
    Replies: 6
    Last Post: 11-07-2009, 07:45 AM
  2. size of buffer
    By silentintek in forum C Programming
    Replies: 10
    Last Post: 10-29-2008, 07:21 PM
  3. Get file size when in buffer
    By Siphon in forum C++ Programming
    Replies: 10
    Last Post: 04-10-2008, 10:52 AM
  4. Input buffer question
    By n3xus in forum C++ Programming
    Replies: 5
    Last Post: 02-01-2006, 08:39 PM
  5. Quick C Question - checking buffer for input
    By sean in forum C Programming
    Replies: 3
    Last Post: 11-13-2004, 11:23 AM

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