Thread: Scanning characters & strings

  1. #1
    Registered User
    Join Date
    Mar 2002

    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
    scanf returns the number of elements it's scanned in, so just do something like
    if (scanf("%c %s", &char1, string)) == 2)
    // both scanned
    // either only 1 scanned or 0 scanned...
    Last edited by cowboyclem; 03-03-2002 at 09:25 PM.

  3. #3
    Registered User
    Join Date
    Aug 2001
    And do switch your scanf() to fgets() for the sake stability!
    kooma -

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, 11:28 AM