Thread: How to enter a line of data in C?

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    15

    How to enter a line of data in C?

    Hi

    I have the code
    Code:
    	printf("Enter the characters:\n");
    	char enc_numbers[10]; //Read in characters
    	gets(enc_numbers);
    Which I am using to read in a line of characters between 1 and 10 (inclusive) characters long. However, if I put this under a previous line using scanf it doesn't work (I'm using scanf to get a single inputted number, which always works).

    I heard that using gets is bad - is this true and how should I read in a line of characters where I don't know how many are going to be entered?

    Thanks

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    • scanf() will, in most circumstances leave a '\n' in the buffer, which, when reading single characters or strings with gets() and fgets(), will be snatched up as your line, thus appearing to be reading nothing. You can add a getchar() to eat the newline char, or don't mix and match functions such as scanf() and fgets().
    • gets() is unsafe, and fgets() should be used in its place. Use stdin as the FILE * parameter, and remember to strip the newline char that fgets() will read (this can be done indirectly with strchr()).

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    gets() is a bad in the sense that there's no way to prevent the user from typing in aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa as the input and thus crashing your program. Use fgets(s, sizeof(s), stdin) instead - that will read at most sizeof(s) characters.

    The other problem, is that scanf and gets aren't "compatible". scanf leaves the separator that ended the input in the input buffer. So there is a newline indicating the end of whatever you read with scanf in the input, ready to end the gets input.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need Help With a BlackJack Program in C
    By Jp2009 in forum C Programming
    Replies: 15
    Last Post: 03-30-2009, 10:06 AM
  2. Payroll- I'm completely stuck
    By stno17 in forum C Programming
    Replies: 7
    Last Post: 11-29-2007, 03:17 AM
  3. How to split up CAN data line
    By rkooij in forum C Programming
    Replies: 6
    Last Post: 03-15-2006, 06:24 AM
  4. Greenhand want help!
    By leereg in forum C Programming
    Replies: 6
    Last Post: 01-29-2002, 06:04 AM
  5. Validating the contents of a char buffer
    By mattz in forum C Programming
    Replies: 3
    Last Post: 12-09-2001, 06:21 PM