Click here to Skip to main content
14,696,609 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good day! Our professor assigned me to do an activity in C that I will present in front of class, but I'm having trouble. I am supposed to create a program that takes user input that identifies if the input is positive, negative, or neutral. If the user inputs a character or a string, it is supposed to output "Invalid Input.". However, I can not seem to make the last condition work. Any tips? I just started so any help will be appreciated. Thank you so much!

What I have tried:

#include <stdio.h>
int main()
	int num;
	printf("Input a number: ");
	scanf("%i", &num);
	if (num>0.0) {
	else if (num<0.0) {
	else if (num==0.0) {
	else {
		printf("Invalid Input");
	return 0; 

I also tried changing the elif statements to if statements but it always included Invalid Input in every output.
Updated 4-Oct-20 8:11am
Rick York 4-Oct-20 12:45pm
First, define what valid input is. Anything else would be invalid input. You should be able to determine what the type of input is you receive.

1 solution

The first issue is that you are reading an integer value and then comparing it to a floating point. So use the simple integral value 0 for your comparison. The second issue is that if you enter a string rather than a number, then scanf will not return anything so num will contain whatever was there before. You need to capture the return value from scanf to check if you read a valid number. Something like:
printf("Input a number: ");
int count = scanf("%i", &num);
if (count != 1)
    printf("Invalid Input");
else // ... now you can check the value of num
CPallini 5-Oct-20 2:10am

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900