need a bit of help with scanf function

This is a discussion on need a bit of help with scanf function within the C Programming forums, part of the General Programming Boards category; hi, im new to programming in C and im sorta stuck looking for some help i wanna write a preogram ...

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    1

    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:

    Code:
    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    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.

    Code:
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 12:48 PM
  5. Replies: 28
    Last Post: 07-16-2006, 11:35 PM

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