Scanning characters & strings

This is a discussion on Scanning characters & strings within the C Programming forums, part of the General Programming Boards category; I'm trying to scan a line. This line will sometimes contain 1 char. or sometimes it will contain 1 char ...

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    8

    Scanning characters & strings

    I'm trying to scan a line. This line will sometimes contain 1 char. or sometimes it will contain 1 char followed by a string.

    printf("\nEnter text now");
    scanf("%c", &char1);
    scanf("%s", %string1);

    this works if i enter both values such as 'c filename' but if i enter just 'c' it crashes.

    i don't really understand how i would go about checking if both are entered or not.

  2. #2
    Registered User
    Join Date
    Jan 2002
    Posts
    2
    scanf returns the number of elements it's scanned in, so just do something like
    if (scanf("%c %s", &char1, string)) == 2)
    // both scanned
    else
    // either only 1 scanned or 0 scanned...
    Last edited by cowboyclem; 03-03-2002 at 08:25 PM.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    129
    And do switch your scanf() to fgets() for the sake stability!
    kooma - t.h@iki.fi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 10-29-2008, 03:22 AM
  2. HELP!!!!emergency Problem~expert please help
    By unknowppl in forum C++ Programming
    Replies: 9
    Last Post: 08-21-2008, 06:41 PM
  3. Replies: 10
    Last Post: 07-10-2008, 03:45 PM
  4. Check strings which should only contain some characters.
    By qingxing2005 in forum C Programming
    Replies: 2
    Last Post: 06-17-2008, 09:32 AM
  5. strings or arrays of characters?
    By Callith in forum C++ Programming
    Replies: 13
    Last Post: 12-26-2004, 10:28 AM

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