scanf question

This is a discussion on scanf question within the C Programming forums, part of the General Programming Boards category; I have a program that takes an array of integers, adds the even values and prints the sum. I have ...

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)

> 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.