Thread: need a bit of help with scanf function

  1. #1
    Registered User
    Join Date
    Sep 2005

    need a bit of help with scanf function

    hi, im new to programming in C and im sorta stuck looking for some help

    i wanna write a preogram that would read in numbers as ascii characters. it will read in a number ie 1234, 1, 3456 or 12 etc.
    and be stored in a character arrray.

    the problem now is how do i make scanf terminate by NOT typing anything but just hitting enter

    part of the code i have for that part is:

    printf("please enter a positive number followed by <enter>:\n");
    scanf ("%s", charArray);
    if (charArray[0] == 0)
         //do something...
    i tried using == '\0' , NULL, '\n' and it wont enter the if loop. any pointers ?? thnx a lot!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    You're better off using fgets() to read a line of input, then using sscanf() to scan the string (if that's what you want to do.

    if ( fgets ( charArray, sizeof charArray, stdin ) != NULL ) {
      if ( charArray[0] == '\n' ) {
        // just pressed enter
      } else {
        int myNum;
        sscanf ( charArray, "%d", &myNum );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. dllimport function not allowed
    By steve1_rm in forum C++ Programming
    Replies: 5
    Last Post: 03-11-2008, 03:33 AM
  4. Replies: 16
    Last Post: 11-23-2007, 01:48 PM
  5. Replies: 28
    Last Post: 07-16-2006, 11:35 PM