Adding system(cls); to program increases startup time - c

When I started writing my program (I didn't add system(cls); at that time), it started the console as soon as I doubled clicked on the exe file. But when I added the system(cls); it took 4-5 seconds to open. Why? Is there any way to fix this?
My Code (it's a simple calculator) -
#include <stdio.h> // for printf() and scanf()
#include <stdlib.h> //for exit() and system()
#include <windows.h> // for SetConsoleTitle()
#include <math.h> // for sqrt()
int calculation();
int main()
{
int afterCal;
SetConsoleTitle("My Calculator");
printf("Welcome to my Calculator\n");
calculation();
for(;;)
{
printf("\nAnother Calculation? type 1\n");
printf("Quit? type 0\n");
scanf( "%d", &afterCal);
if (afterCal == 1)
{
system("cls");
calculation();
}
else if (afterCal == 0)
{
exit(0);
}
else
{
system("cls");
printf("\nError, enter 0 or 1\n");
}
}
return 0;
}
int calculation()
{
double num1, num2;
char ope, square = 251;
printf("Enter number 1 -\n");
scanf("%lf", &num1);
printf("Enter number 2 (put 0 if you want square/cube root or cube) -\n");
scanf("%lf", &num2);
if (num2 == 0)
{
printf("Enter operation - s for square root, r for cube root, c for cube\n");
}
else
{
printf("Enter operation - +, -, *, /\n");
}
scanf(" %c", &ope);
switch (ope)
{
case '+':
system("cls");
printf("%g + %g = %g\n", num1, num2, num1 + num2);
break;
case '-':
system("cls");
printf("%g - %g = %g\n", num1, num2, num1 - num2);
break;
case '*':
system("cls");
printf("%g * %g = %g\n", num1, num2, num1 * num2);
break;
case '/':
system("cls");
printf("%g / %g = %g\n", num1, num2, num1 / num2);
break;
case 's':
system("cls");
printf("%c%g = %g\n", square, num1, sqrt(num1));
break;
case 'r':
system("cls");
printf("Cube root of %g = %g\n", num1, cbrtf(num1));
break;
case 'c':
system("cls");
printf("Cube of %g = %g\n", num1, num1 * num1 * num1);
break;
default:
system("cls");
printf("Error, invalid operation %c\n", ope);
break;
}
return 0;
}
Any help would be appreciated!

1st I was using the MinGW x64 compiler (at that time the startup delay occurred), but now I am using Visual Studio 2022 ide and its compiler, and my exe opens instantly! Problem Solved!
But I am still confused, why did MinGW give that much startup delay...

Related

scanf fails when I type in operations (+,-,*,/ etc) in C

I am working on building a calculator in C, and have encountered a problem regarding scanf for characters. I have defined a "string" called operationValue, but when I try to do the scanf function (the one that I have a comment right next to it), it immediately prints out an invalid character instead of the operation I typed in. I needed the string instead of just a character because I have the other operation for powers and roots, but even they don't work when I type them in. When I complete the code it prints "Not Valid Operation."
Sorry if this is not what is conventional in stack overflow, but this is the first time I'm on here. If the pieces of code are too long or something, please help me edit it so I can learn not to do that next time.
#include <stdio.h>
void theOperation(double num1, char operationValue, double num2)
{
if(operationValue == "+")
{
printf("%lf\n", num1 + num2);
} else if(operationValue == "-")
{
printf("%lf\n", num1 - num2);
} else if(operationValue == "*")
{
printf("%lf\n", num1 * num2);
} else if(operationValue == "/")
{
printf("%lf\n", num1 / num2);
} else if(operationValue == "pow")
{
printf("%lf\n", pow(num1, num2));
} else if(operationValue == "root")
{
printf("%lf\n", pow(num1, (1/num2)));
} else
{
printf("Not valid operation");
}
}
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %s", &operationValue);
printf("%c\n", operationValue); // This line fails when I type in any operation I define: '+', '-', '*', '/' 'pow' 'root'
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
Use the "%s" for reading and printing the operator:
#include <stdio.h>
#include <math.h>
#include <string.h>
void theOperation(double num1, char* operationValue, double num2)
{
if(strcmp(operationValue, "+") == 0)
{
printf("%lf\n", num1 + num2);
} else if(strcmp(operationValue, "-") == 0)
{
printf("%lf\n", num1 - num2);
} else if(strcmp(operationValue,"*") == 0)
{
printf("%lf\n", num1 * num2);
} else if(strcmp(operationValue,"/") == 0)
{
printf("%lf\n", num1 / num2);
} else if(strcmp(operationValue,"pow") == 0)
{
printf("%lf\n", pow(num1, num2));
} else if(strcmp(operationValue, "root") == 0)
{
printf("%lf\n", pow(num1, (1/num2)));
} else
{
printf("Not valid operation");
}
}
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %9s", &operationValue);
printf("%c\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
Scanf() docs: https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
-- EDIT --
I have updated the code to a working one.
I also updated the scanf() for reading the operator like #M. Nejat Aydin commented for prevent buffer overrun
The code has several defects:
The function signature given:
int theOperation(num1, operationValue, num2)
is incorrect. You must define the datatype alongside the identifier.
The function returns int but nowhere used.
A variable char[10] passed into a function which accepts char, which will obviously give unexpected results.
If you want to use mathematical functions like pow(), sqrt(), floor(), etc., you must define the header file math.h. They're not available in stdio.h (that only contains I/O operation functions and subroutines).
Code redefined:
#include <stdio.h>
// return type set to: void, datatypes defined for function parameters
void theOperation(double num1, char operationValue, double num2)
{
double result = 0;
// calculating the results based on operations
switch (operationValue) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
default:
printf("No such operation found.\n");
break;
}
printf("Result: %lf\n", result);
}
int main(void)
{
double num1, num2;
char operationValue;
printf("This is a calculator.\n");
printf("Enter first and second number: ");
scanf("%lf %lf", &num1, &num2);
printf("%lf %lf\n", num1, num2);
printf("Enter operation: ");
scanf(" %c", &operationValue);
printf("%c\n", operationValue);
// the operation execution
theOperation(num1, operationValue, num2);
return 0;
}
The explanation is pretty much simple.
The scanf() takes the necessary data from the user and then passes the parameters to the function theOperation() with their appropriate arguments. Thereafter, the switch statements tries to match which expression is given in case statements are identical to the operationValue.
When it does finds one, it simply evaluates the expression and prints the result.
Note: If you just want to compare single letters like +, -, *, /, etc. then you still don't need to use character array to compare them using strcmp() or anything.
It gives the following output:
This is a calculator.
Enter first and second number: 10 50
10.000000 50.000000
Enter operation: -
-
Result: -40.000000
%c in scanf() is for reading one character. You should use %(max length)s to read strings (that don't contain whitespace characters). The (max length) should be buffer size minus one (for terminating null-character). Also note that %(max length)s will take char*, so you shouldn't put & before arrays.
%c in printf() is for printing one character. You should use %s to print strings.
#include <stdio.h>
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %9s", operationValue);
printf("%s\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
return 0;
}
It wasn't too hard to fix your code by adding types and ensuring the arguments get passed through correctly:
#include <stdio.h>
#include <stdlib.h>
void theOperation(double num1, char operationValue, double num2)
{
switch (operationValue) {
case '+':
printf("%lf\n", num1 + num2);
break;
case '-':
printf("%lf\n", num1 - num2);
break;
case '/':
printf("%lf\n", num1 / num2);
break;
case '*':
printf("%lf\n", num1 * num2);
break;
default:
printf("Not valid operation");
}
}
int main()
{
double num1, num2;
char operationValue;
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %c", &operationValue);
printf("%c\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
I made fixes in function parameters, strings vs. chars and wrong scanf format chars, taking all your operations including "pow" and "root" and combining it with switch():
#include <stdio.h>
#include <math.h>
#include <string.h>
void theOperation(double num1, const char *operationValue, double num2)
{
switch(*operationValue) {
case '+': printf("%lf\n", num1 + num2); break;
case '-': printf("%lf\n", num1 - num2); break;
case '*': printf("%lf\n", num1 * num2); break;
case '/': printf("%lf\n", num1 / num2); break;
default: {
if(!strcmp(operationValue, "pow")) {
printf("%lf\n", pow(num1, num2));
} else if(!strcmp(operationValue, "root")) {
printf("%lf\n", pow(num1, (1/num2)));
} else printf("Not valid operation\n");
break;
}
}
}
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf("%9s", operationValue);
printf("operation entered: %s\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
Output example with "power":
$ gcc -Wall -o calc calc.c ;./calc
This is a calculator.
Enter first number: 2
2.000000
Enter operation: pow
operation entered: pow
Enter second number: 3
3.000000
8.000000
This is an important line:
scanf("%9s", operationValue);
(Read a string with up to 9 chars.)

How to check whether the entered symbol is char or not?

I have a problem with calculator. I want to program a calculator, but it "works" with letters too. If I enter f.e letters "s" and "u", i get answer 0. How to repair that?
# include <stdio.h>
int main() {
char operator;
int a,b;
printf("Enter the operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two number and seperate them with space: ");
scanf("%lf %lf",&a, &b);
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("% 2lf - %.2lf = % 2lf",a, b, a - b);
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
printf("%.2lf / %.2lf = %.2lf",a, b, a / b);
break;
default:
printf("Error!");
}
return 0;
}
Sorry, if the question has been up here.
The link to answer is also appreciated!
Cheers!
I have made the corrections discussed in comments
#include <stdio.h>
int main(void) { // correct definition
char operator;
double a,b; // correct type
printf("Enter the operator (+, -, *, /): ");
if(scanf("%c", &operator) != 1) { // add error check
puts("Bad operator entered");
return 1;
}
printf("Enter two number and seperate them with space: ");
if(scanf("%lf %lf",&a, &b) != 2) { // add error check
puts("Bad value(s) entered");
return 1;
}
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("%.2lf - %.2lf = % 2lf",a, b, a - b); // corrected typo
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
printf("%.2lf / %.2lf = %.2lf",a, b, a / b);
break;
default:
printf("Error!");
}
return 0;
}
UPDATED:
i found my Ooldest code in library Folder maybe it helps you in that problem. This will definitely Work.
char operator;
printf("Enter the Operation in ( * , / , - , + )");
scanf("%s",&operator);
if(operator!='+' || operator!='-' || operator!='*' || operator!='/')
{
return 0;
}
I got it working. It was easier to do than I thought.
So the right code, I'll put comment to answer.
#include
int main(void) { // correct definition
char operator;
double a,b; // correct type
printf("Enter the operator (+, -, *, /): ");
if(scanf("%c", &operator) != 1) { // add error check
puts("Bad operator entered");
return 1;
}
printf("Enter two number and seperate them with space: ");
if(scanf("%lf %lf",&a, &b) != 2) { // add error check
puts("Bad value(s) entered");
return 1;
}
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("%.2lf - %.2lf = % 2lf",a, b, a - b); // corrected typo
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
if(b!=0){ //added an if-sentence
printf("%.2lf / %.2lf = %.2lf\n",a, b,
a / b);
}
else
printf("Can't divide by zero\n");
break;
default:
printf("Error!");
}
return 0;
}
Basically, I just put an if-sentence to case('/').

Floating point exception (core dumped) - c program

I have a question on one of my assignements:
Write a program that allows the user to type in simple expressions of the form
number operator number
The program evaluates the expression and displays the results at the terminal, to two decimal places of accuracy.
The program, however, is allowed to call the scanf function only once.
#include <stdio.h>
int main(void)
{
int num1, num2, sum, difference, product, quotient;
num1 = 0;
num2 = 0;
printf("type in expression");
scanf("%d%d", &num1, &num2);
sum = num1+num2;
difference = num1-num2;
product = num1*num2;
quotient = num1/num2;
switch (num1) {
case 2: printf("%d/%d=%d", num1, num2!=0 , quotient);
break;
case 1: printf("%d*%d=%d", num1, num2, product);
break;
case 0: printf("%d-%d=%d", num1, num2, difference);
break;
default: printf("%d+%d=%d", num1, num2, sum);
break;
}
}
The program can be compiled, but when I run it, this message shows up:
Floating point exception (core dumped)
What does this mean? Also, if there is anything else wrong with it, please let me know.
I think this is what you need.
#include <stdio.h>
int main(void)
{
int num1=0, num2=0;
char operation= ' ';
printf("type in expression\n");
scanf("%d %c %d", &num1, &operation, &num2);
switch (operation) {
case '/': {
if(0 == num2) //This is the solution for your issue.
{
printf("\nCan not perform %d/%d", num1, num2);
}
else
{
printf("\n%d / %d=%d", num1, num2, num1/num2);
}
}
break;
case '*': printf("\n%d * %d=%d", num1, num2, num1*num2);
break;
case '-': printf("\n%d - %d=%d", num1, num2, num1-num2);
break;
case '+': printf("\n%d + %d=%d", num1, num2, num1+num2);
break;
default: printf("\nInvalid operation[%c]", operation);
break;
}
return 0;
}

Struggling to program a simple calculator

I am trying to program a simple calculator. Here is my code first:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char operator = 0;
float num1 = 0.0;
float num2 = 0.0;
float sol = 0.0;
while (operator != 'q') {
printf("Operator: ");
scanf("%c", &operator);
printf("First Number: ");
scanf("%f", &num1);
printf("Second Number: ");
scanf("%f", &num2);
switch (operator)
{
case '+': sol = num1 + num2; break;
case '-': sol = num1 - num2; break;
case '*': sol = num1 * num2; break;
case '/': sol = num1 / num2; break;
case 'q': printf("Finished!"); exit(0);
default: printf("Error!"); exit(0);
}
printf("The solution is: %.2f\n\n", sol);
}
return 0;
}
So for me the code is fine. As you can see I did this with a while loop that lets you calculate until you type in 'q' as operator. The first run of the loop works fine but then it gets creepy (my console):
Operator: +
First Number: 5
Second Number: 4
The solution is: 9.00
Operator: First Number:
Why does the program not let me enter an operator in the second loop run?
Most format specifiers with scanf will skip leading whitespace. %c does not.
scanf("%f", &num2); at the end of the first iteration leaves a newline in the input buffer.
scanf("%c", &operator); at the start of the second iteration, reads the newline and proceeds.
using a space before %c in scanf(" %c", &operator); will allow %c to skip the leading whitespace and capture the operator.
You should check scanf for errors:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char operator = 0;
float num1 = 0.0;
float num2 = 0.0;
float sol = 0.0;
while (operator != 'q') {
printf("Operator: ");
if((scanf(" %c", &operator)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
printf("First Number: ");
if((scanf("%f", &num1)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
printf("Second Number: ");
if((scanf("%f", &num2)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
switch (operator){
case '+': sol = num1 + num2; break;
case '-': sol = num1 - num2; break;
case '*': sol = num1 * num2; break;
case '/': sol = num1 / num2; break;
case 'q': printf("Finished!"); exit(0);
default: printf("Error!"); exit(0);
}
printf("The solution is: %.2f\n\n", sol);
}
return 0;
}
and as you can see I changed scanf("%c", &operator); to this scanf(" %c", &operator); to make scanf to ignore (skip) Whitespace.

how to repeat a c program from the beginning and clean the screen and 1st input values?

i m new in programing.
i've written a simple program.
i want to repeat the program again and again and it can only exit when user wants to exit.
here is my program
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
int num1, num2, a, m, s, choice;
float d;
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Any Key To Exit");
getch();
return 0;
}
and here is the output
"Enter The First Number: 10
Enter The Second Number: 10
Enter Your Choice
For Addition Type A
For Multipication Type M
For Division Type D
For Substraction Type S : A
The Addition Of The Number Is= 20
Press Any Key To Exit"
I want a line before the line Press Any Key To Exit
"If You Want To Calculate Again Press Y
or
Press Any Key To Exit"
when press Y then the program should start from the beginning.
How can i do this???
wrap the code inside a do{} while() ?
char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');
Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.
You can also use recursion, which is often used in more functional oriented programming languages.
Pseudo-code:
myfunction = do
...
b <- somethingtodo
...
if b
then myfunction
else return ()
Relative to Jens's solution, it would look like:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
char choice;
int num1, num2, cont;
printf("Enter the first number: ");
scanf("%d", &num1);
getchar ();
printf("Enter the second number: ");
scanf("%d", &num2);
getchar ();
printf("A - addition\n");
printf("S - subtraction\n");
printf("M - multiplication\n");
printf("D - division\n");
printf("[ASMD]? ");
choice = (char)toupper(getchar());
getchar ();
printf("\n");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
printf("Continue [YN]? ");
cont = toupper(getchar());
getchar ();
if (cont == 'Y')
return main(); // the difference.
else if (cont == 'N')
return EXIT_SUCCESS;
}
}
I would move the calculation stuff in it's own function and then use while() in main.
I have tried to fix other problems as well (this solution only uses standard C functions).
#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper
char fail_on_eof (int c)
{
if (c == EOF)
exit (EXIT_FAILURE);
// In case of fail_on_eof (scanf (...)) the return value of this this
// function is not useful
// scanf () returns the number of chars read or EOF
// getchar () returns a char or EOF
return (char) c;
}
void skip_to_next_line (void)
{
char c;
do
{
c = fail_on_eof (getchar ());
} while (c != '\n');
}
char read_upcase_char_line (char* prompt)
{
char c;
printf ("%s ", prompt);
c = fail_on_eof (toupper (getchar ()));
skip_to_next_line ();
return c;
}
int read_num_line (char* prompt)
{
int num;
printf ("%s ", prompt);
fail_on_eof (scanf ("%d", &num));
skip_to_next_line ();
return num;
}
int calculate (void)
{
char choice;
int num1, num2, cont;
num1 = read_num_line ("Enter the first number:");
num2 = read_num_line ("Enter the second number:");
puts("A - addition");
puts("S - subtraction");
puts("M - multiplication");
puts("D - division");
choice = read_upcase_char_line ("[ASMD]?");
puts("");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
// Better use stderr for error messages
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
// Better use stderr for error messages
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
cont = read_upcase_char_line ("Continue [YN]?");
if (cont == 'Y')
return -1;
else if (cont == 'N')
return 0;
}
}
int main(void)
{
while (calculate ());
return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}

Resources