Thread: scanf only octals

  1. #1
    Registered User
    Join Date
    Apr 2021
    Posts
    8

    scanf only octals

    Hi I would like to allow scanf to scan only numbers from 0 to 7 all the other numbers should give out a print message like error or similar. It doesn't seem to work. Can anyone give me an advice, I would like to do it as simple as possible as my experience in c is almost non existent.
    This is how I want to start but it seems not to work properly, what am I doing wrong?
    insert
    Code:
    main ()
    { int x;
       printf("Input a number from 0 to 7\n");
       scanf("%[0-7]o", &x);
       printf("The number is x=%o", x);
    return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > scanf("%[0-7]o", &x);
    You're over thinking it.

    scanf("%o", &x);

    But if you're looking to actually complain to the user if they type in "007JamesBond", then you first need to read a line of input using fgets(), then validate the whole line before doing the conversion.
    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. Sum of octals found in input
    By rmmstn in forum C Programming
    Replies: 6
    Last Post: 11-26-2020, 07:52 AM
  2. scanf
    By mnml in forum C Programming
    Replies: 9
    Last Post: 11-19-2011, 07:52 PM
  3. comparing octals???
    By TaiL in forum C Programming
    Replies: 1
    Last Post: 10-13-2009, 12:55 PM
  4. First scanf() skips next scanf() !
    By grahampatten in forum C Programming
    Replies: 5
    Last Post: 08-17-2004, 02:47 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM

Tags for this Thread