954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Simple Program will not exit gracefully

Hi, everyone. You may have probably heard this a hundred times, but I am new to programming and I am taking an intro to C++ class. I have a program that I have written, but I can't understand why it will not exit gracefully.
This is what I have written, but if I type in "E" to exit, it loops to enter in a number again and doesn't exit.
printf("\nEnter one positive or negative number (1, 2, 3. . . or E to exit): ");

/*multiple lines comment - Program to display square and square root for a given number*/
#include <math.h>/*for sqrt( ) function*/
#include <stdio.h>
#include <stdlib.h>   
int main(void)
{
 /*variable and data type*/
 float x;
 
 /*standard output*/
 printf("Shannon says programming is hard!\n"); 
 printf("\nEnter one positive or negative number (1, 2, 3. . . or E to exit): ");
 /* Prompt for input again */ printf(">>  ");
 /*standard input*/
 scanf("%f", &x);
 printf("\nx = %f ", x);
 printf("\nSquare for x is = %f", x * x);
 //sqrt() is the predefined function, defined in math.h
 printf("\nSquare root for x is = %f\n", sqrt(x));//print results;
 return 0;//finished
}


Any help would be greatly appreciated!


<< moderator edit: added [code][/code] tags >>

Starz20
Newbie Poster
3 posts since Apr 2005
Reputation Points: 10
Solved Threads: 0
 
This is what I have written, but if I type in "E" to exit, it loops to enter in a number again and doesn't exit.

I don't see the loop, but"E" is not a valid float number. If you want the possibility of the user input to be either text or a number, read the input as a string. Then, if the string is not "E", (attempt to) convert the input string into a float.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Thank you, Dave. I am still learning! :)

Starz20
Newbie Poster
3 posts since Apr 2005
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You