This question already has answers here:
Check if input is float else stop
(6 answers)
Closed 7 years ago.
So, I'm creating a program that calculates the area of a triangle, and I need it to tell the user if he typed a letter or a negative number, in order, I created the code:
I need to use isdigit
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform the value of side A.");
fflush(stdin);
scanf("%f",&a);
while(a<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&a);
}printf("Inform the value of side B.");
fflush(stdin);
scanf("%f",&b);
while(b<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&b);
}printf("Inform the value of side C.");
fflush(stdin);
scanf("%f",&c);
while(c<=0||isdigit((int)a)){
printf("Invalid value.");
fflush(stdin);
scanf("%f",&c);}
s=((a+b+c)/2);
ar1=(s*(s-a)*(s-b)*(s-c));
ar2=pow(ar1,0.5);
printf("The semiperimeter is %f",s);
printf("The area of the triangle is%f",ar2);
system ("pause");
return 1;
}
But, when I compile/run it, and type "x", or "blabla" when I was supposed to type a number, nothing happens, and the program doesn't warn me, what should I do?
First of all, using fflush on stdin is Undefined Behavior as per the C11 standard, although it is well defined on some implementations.
Secondly, you can't use simply use isdigit that way. Once %f sees invalid data such as characters, the scanf terminates and the corresponding argument is left untouched. Also, using isdigit on an uninitialized variable leads to Undefined Behavior.
What you can do is check the return value of scanf. All the three scanfs in your code returns 1 if successful.
Fixed Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h> //Unused header
void flushstdin() //Removes all characters from stdin
{
int c;
while((c = getchar()) != '\n' && c != EOF); //Scan and discard everything until a newline character or EOF
}
int main () {
float a, b, c;
float s=0, ar1=0, ar2=0;
printf("Inform the value of side A\n");
//fflush(stdin); Avoid this to make your code portable
while(scanf("%f",&a) != 1 || a <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
printf("Inform the value of side B\n");
//fflush(stdin);
while(scanf("%f",&b) != 1 || b <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
printf("Inform the value of side C\n");
//fflush(stdin);
while(scanf("%f",&c) != 1 || c <= 0){
printf("Invalid value\n");
flushstdin(); //Alternative way to flush stdin
}
s=((a+b+c)/2);
ar1=(s*(s-a)*(s-b)*(s-c));
ar2=pow(ar1,0.5);
printf("The semiperimeter is %f\n", s);
printf("The area of the triangle is %f\n", ar2);
system ("pause");
return 0; // 0 is usually returned for successful termination
}
Also, it is better to add newline characters at the end of the strings in printf as seen in the above program. They
Improve readability
Flushes the stdout
Related
This question already has answers here:
getchar does not stop when using scanf
(5 answers)
Closed 3 years ago.
I started C just a while ago (same as coding), so I`m a noob.
My Goal:
to state that the user hasn't entered a or b and then wait for the user to press enter to return to the calculator menu.
My problem:
getchar() doesn't wait for me to press enter. (Case 3)
#include <stdlib.h>
int main()
{
for (int i = 0;i == 0;){
int options=0,enteredA=0, enteredB=0;
float *a, A, *b, B, *c, C;
a=&A,b=&B,c=&C;
printf ("Calculator\nAvailable options:\n[1]Enter value for A\n[2]Enter value for B\n[3]Addition\n[9]Exit\n");
scanf ("%d",&options);
system ("clear");
switch (options) {
case 1:
printf("Enter a value for A:");
scanf ("%f",&*a);
enteredA++;
break;
case 2:
printf("Enter a value for B:");
scanf ("%f",&*b);
enteredB++;
break;
case 3:
if ((enteredA==0) | (enteredB== 0)){
printf("A and B are not initialized yet. Please enter a value in the menu.\nPress [Enter] to continue to the menu:\n");
fflush(stdin);
getchar();
break;
} else{
printf("%f+%f=%f\n",*a,*b,*c=*a+*b);
fflush(stdin);
getchar();
break;
}
break;
case 9:i++;break;
}
system("clear");
}
printf("Calculator Shut Down");
return 0;
}
In the following line:
scanf ("%d",&options);
you actually enter a number, and a newline character. The scanf function reads only the number. It leaves the newline (\n) in the input stream.
When you call getchar(), it will find a newline in the input stream. Hence, it will read it without waiting for user input. It only wait for user input if it didn't find anything in the input stream.
A possible workaround for this is to call getchar two times instead of one.
The first call will read the already existing newline in the stream. The second call won't find anything in the input stream. So, it will wait for user input as you expect.
I have some small comments that aren't related to your question:
You use scanf ("%f",&*a);. Why not just scanf("%f", a); or scanf("%f", &A); ?
Why you even create a pointer a for the variable A ?
I don't think you really need the variable c as well.
You don't need the variable i in the loop as well.
At the beginning of the loop, you keep re-initializing enteredA and enteredB variables to zero. That way, the condition in case 3: will be always true. You need to move these variables outside of the loop.
Your code also missing a #include <stdio.h>.
I'd simplify things like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int enteredA = 0, enteredB = 0;
while (1)
{
int options;
float A, B;
printf ("Calculator\nAvailable options:\n[1]Enter value for A\n[2]Enter value for B\n[3]Addition\n[9]Exit\n");
scanf("%d", &options);
getchar(); // The extra getchar to read the newline left in the stdin.
system ("clear");
switch (options)
{
case 1:
printf("Enter a value for A:");
scanf("%f", &A);
enteredA++;
break;
case 2:
printf("Enter a value for B:");
scanf ("%f", &B);
enteredB++;
break;
case 3:
if (enteredA ==0 || enteredB == 0)
{
printf("A and B are not initialized yet. Please enter a value in the menu.\nPress [Enter] to continue to the menu:\n");
}
else
{
printf("%f + %f = %f\n", A, B, A + B);
}
getchar();
break;
case 9:
printf("Calculator Shut Down");
return 0;
}
system("clear");
}
}
I have written this simple program, which is supposed to calculate the factorial of a number entered by the user. The program should ask the user to stop or continue the program in order to find the factorial of a new number.
since most of the time user don't pay attention to CapsLock the program should accept Y or y as an answer for yes. But every time I run this program and even though I enter Y/y , it gets terminated !
I googled and found out the problem could be due to new linecharacter getting accepted with my character input so, I modified the scanf code from scanf("%c", &choice); to scanf("%c ", &choice); in order to accommodate the new line character , but my program is still getting terminated after accepting Y/y as input.
Here is the code . Please if possible let me know the best practices and methods to deal with these kinds of issues along with the required correction.
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
I'm a beginner in programming and I'm running this code in visual studio 2015.
Just modify your scanf like following:
printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
also you should use:
} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
NOTE:
Simple quote ' is used for characters and double quote " is used for string
Your second-last line has a string literal "y", which should be a character literal i.e. 'y':
} while (choice =="y" || choice =="Y");
This should be:
} while (choice =='y' || choice =='Y');
Also, your scanf() doesn't consume whitespace. Add a space before %c to make it ignore newlines or other spaces:
scanf(" %c", &choice);
Try doing the following even after the correction there are still some bugs in the code
In your code if you type 'Y' and recalculate a factorial it gives wrong answer as
int factorial is already loaded with the previous value
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace System;
using namespace std;
int calculateFactorial(int i);
int main()
{
int i;
char choice;
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
printf("\n The factorial of entered no is :\t %d", calculateFactorial(i));
printf("\n Do you want to continue (Y/N)?");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
int calculateFactorial(int i) {
int factorial = 1;
if (i == 0){
factorial = 1;
}else {
while (i > 0){
factorial = factorial*i;
i--;
}
}
return factorial;
}
I can't understand why this does exactly what I want. The part where I used two scanf's in the loop confuses me. I compiled it using devcpp.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int dend, dsor, q, r;
char c;
while(c!='n')
{
printf("enter dividend: ");
scanf("%d", &dend);
printf("enter divisor: ");
scanf("%d", &dsor);
q=dend/dsor;
r=dend%dsor;
printf("quotient is %d\n", q);
printf("remainder is %d\n", r);
scanf("%c", &c);
printf("continue? (y/n)\n");
scanf("%c", &c);
}
system("PAUSE");
return 0;
}
FWIW, your code invokes undefined behavior. In the part
char c;
while(c!='n')
c is an uninitialized local variable with automatic storage and you're trying to use the value of c while it is indeterminate.
That said, first scanf("%c", &c); is used to eat up the newline present in the input buffer due to the press of enter key after previous input. You can read about it in details in another post.
#define f(x) (x*(x+1)*(2*x+1))/6
void terminate();
main()
{
int n,op;
char c;
printf("Enter n value\n");
scanf("%d",&n);
op=f(n);
printf("%d",op);
printf("want to enter another value: (y / n)?\n");
scanf("%c",&c); // execution stops here itself without taking input.
getch();
if(c=='y')
main();
else
terminate();
getch();
}
void terminate()
{
exit(1);
}
In the program above , I want to take input from the user until he enters an n value.
For this I'm trying to call main() function repeatedly . If it is legal in C , I want to know why the program terminates at the scanf("%c",&c) as shown in commented line.
Someone , please help.
You should never call main from within your program. If you need to run it more then once use a while loop inside it.
Your execution stops because by default stdin in a terminal is line buffered. Also you are not using the return value from getch.
int main()
{
int n,op;
char c;
do {
printf("Enter n value\n");
scanf("%d",&n);
op=f(n);
printf("%d",op);
printf("want to enter another value: (y / n)?\n");
scanf("%c",&c);
} while (c == 'y')
return 0;
}
You first have
scanf("%d",&n);
which you have to press the Enter key for it to accept the number.
Later you have
scanf("%c",&c);
There is a problem here, which is that the first call to scanf leaves that Enter key in the input buffer. So the later scanf call will read that.
This is easily solved, by changing the format string for the second scanf call just a little bit:
scanf(" %c",&c);
/* ^ */
/* | */
/* Note space here */
This tells the scanf function to skip leading whitespace, which includes newlines like the Enter key leaves.
It's legal, but you'll have a STACKOVERFLOW after a while (pun intended).
What you need is a loop:
while (1) {
printf("Enter n value\n");
scanf("%d",&n);
op=f(n);
printf("%d",op);
printf("want to enter another value: (y / n)?\n");
scanf("%c",&c); // execution stops here itself without taking input.
getch();
if(c != 'y')
break;;
}
I'm just starting to learn C and I'm having problem with stopping my program based on what the user inputted.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a;
int b;
char c[5];
printf("Enter the two values you like to compare, type stop to end.\n");
while (c != "stop")
{
scanf_s(" %d %d %s", &a, &b, &c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
printf("Thanks for playing.");
getchar();
return 0;
}
The problem that I'm having is having to put in another variable, c, in my scanf_s. How would I do it so that the user does not have to put in another word after the 2 numbers? Also how can I check if the user only input "stop" so that it will stop the program? Btw the way I have it right now also does not stop the program when I do "10 10 stop". Thanks.
remove & for c in scanf_s(" %d %d %s", &a, &b, &c);
use strcmp to compare strings.
if you need to ignore case while comparing use strcasecmp (for UNIX based systems) and stricmp (for windows).
Use do-while instead of while if you need to run the loop at least once.
Full Working Code:
#include <stdio.h>
#include <string.h>
int main()
{
int a;
int b;
char c[5] = {'\0'};
do {
printf("Enter the two values you like to compare, type stop to end.\n");
scanf("%d%d%s", &a, &b, c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
while (strcmp(c,"stop"));
printf("Thanks for playing.");
getchar();
return 0;
}
while (c != "stop")
You cannot compare strings in C like that, use memcmp() or strncmp() library functions available in string.h. Read about them to know how they can be implemented as condition in while loop.
Also, to get string input, use
scanf_s(" %d %d %s", &a, &b, c); // Remove that litle '&' before 'c'.
NOTE: The function scanf_s returns the number of inputs scanned correctly, you should check that before proceeding with input values.
To get the user to stop without explicitly entering "stop", many ways are there:
1) Use do-while loop and keep asking user if he wants to play more.
2) Use negative numbers input (say -1) to quit.
Use line below to make sure your 'c' scan your string entered.
scanf(" %d %d %s", &a, &b, c);
Edit:
Consider replacing your while with line below to make sure you stop works. Include "string.h"
while (strcmp(c,"stop"))
Here is the fixed version... I have add the comments in the code for understanding...
#include <stdio.h>
#include <string.h>
int main()
{
int a;
int b;
char c[5] = {'\0'};
printf("Enter the two values you like to compare, type stop to end.\n");
while (strcmp(c,"stop"))
{
scanf("%d%d%s", &a, &b, c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
printf("Thanks for playing.");
getchar();
return 0;
}
First, lets correct your program:
&c (third argument to scanf_s) is incorrect. It should be c (because it is already a pointer). According to docs, scanf_s requires sizes to be specified for all %s format strings; therefore, the way you are doing things now, you should have written scanf_s(" %d %d %4s", &a, &b, c);
The program would be much easier to use if you changed your logic to "enter a blank line to exit". You can test this looking at the return value of scanf_s, which will be the number of format strings correctly read from the input.
If you need to ask for strings, then allow either, and look at whatever the user wrote to see whether it was number or string:
#include <stdio.h>
#include <string.h>
int main() {
int a;
int b;
char c[32];
printf("Enter the two values to compare, or type stop to end.\n");
while (fgets(c, 31, stdin) != NULL && strncmp("stop\n", c)) != 0) {
// user did not request to exit and wrote something; maybe 2 numbers
if (sscanf(c, "%d %d", &a, &b) != 2) {
// but he did not write two numbers. Complain and repeat.
printf("please write two numbers to compare, or type stop to end.\n");
continue;
}
if (a == b) {
printf("both are equal\n");
} else {
printf("both are not equal\n");
}
}
printf("Thanks for playing.\n");
return 0;
}
fgets reads whole lines, and you can then try to parse them using sscanf. This has the advantage over common scanf that you can try to parse the same line in different ways, depending on what you find in it. Generally, you do not want to fill your code with getchar(). If you are debugging, your debugger will stop for you. If you are not debugging, you will want to test or use your program with input redirection, and getchar() is simply not needed.
Its because you are using &c instead of just c in scanf_s. Replace that and it should work. Also, c is a string, so, you have to use strcmp instead of !=.
An easier way to write this code would be::
int main()
{
int a;
int b;
char c;
do
{
printf("Would you like to play?\nPress 'Y' for 'Yes' or 'N' for 'No'\n");
scanf( "%c", &c ) ;
/*scanf_s( "%c", &c, 1 ) ; */
if( c != 'Y' && c != 'y' )
break ;
printf("Enter the two values you like to compare\n" ) ;
scanf(" %d %d", &a, &b);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}while(1) ;
printf("Thanks for playing.");
getchar();
return 0;
}