Thread: Input buffer size question?!

  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
    28,413
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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, 08: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, 09:39 PM
  5. Quick C Question - checking buffer for input
    By sean in forum C Programming
    Replies: 3
    Last Post: 11-13-2004, 12:23 PM