Thread: scanf question

  1. #1
    back? dbaryl's Avatar
    Join Date
    Oct 2001
    Posts
    597

    scanf question

    I have a program that takes an array of integers, adds the even values and prints the sum. I have a loop that scans in the values for each integer in the array separately, and if the integer is even, it's added to the sum.

    The program works, but I want to make sure the values scanned are INTEGERS, not doubles or characters... (this is my first array program, I'm new to programming)

    This is the idea that I have:

    Code:
    if (scanf ("%d", &array[i]))
    {
    	/* do stuff here */
    	if (array[i] % 2 == 0)
    	sum = sum + array[i];
    }
    else 
    printf ("Please enter an INTEGER.\n");
    I think this makes sure that the scanned value is either an integer or a double, and I can clear the buffer with rewind (stdin);

    If you can please help me figure out how make sure the value is an INT and not a DOUBLE, I'd be forever thankful Thanks peoplez

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > if (scanf ("%d", &array[i]))
    First off, you should check this result is actually == 1. scanf can also return EOF, which would also evaluate to true.

    The basic problem is telling the difference between "123" and "123.456" - both of which the above scanf call will parse successfully.

    Then you need to know that scanf stops at the first character which doesn't match the current conversion.

    In the case of an integer, this will either be a space or a newline character.

    If it's a float, then the next character will be a '.'

    For mangled input (a string), or a number followed by a string (eg "123ABC"), then you should just throw the input away.

    It's generally easier if you read the input with fgets, then you can have several goes at parsing the line with sscanf (or other techniques). scanf is single pass, so you have to be more careful at deciding whats coming next.
    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. Replies: 7
    Last Post: 05-25-2006, 12:51 PM
  2. Exam Question - Possible Mistake?
    By Richie T in forum C++ Programming
    Replies: 15
    Last Post: 05-08-2006, 03:44 PM
  3. Scanf Question
    By shiyu in forum C Programming
    Replies: 4
    Last Post: 01-31-2003, 08:48 AM
  4. Simple question with scanf()
    By MadStrum! in forum C Programming
    Replies: 3
    Last Post: 01-20-2003, 10:41 AM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM