y/n loop at the end of a function - c

good evening,
Here is my code. I am making a little calculator but I'm battling at the end to make the function repeat with a y/n loop. I have looked at others but can't seem to get the right answer.
Thanks.
#include <stdio.h>
int main()
{
int n, num1, num2, result;
char answer;
{
printf("\nWhat operation do you want to perform?\n");
printf("Press 1 for addition.\n");
printf("Press 2 for subtraction.\n");
printf("Press 3 for multiplication.\n");
printf("Press 4 for division.\n");
scanf("%d", &n);
printf("Please enter a number.\n");
scanf("%d", &num1);
printf("Please enter the second number.\n");
scanf("%d", &num2);
switch(n)
{
case 1: result = num1 + num2;
printf("The addition of the two numbers is %d\n", result );
break;
case 2: result = num1 - num2;
printf("The subtraction of the two numbers is %d\n", result );
break;
case 3: result = num1 * num2;
printf("The multiplication of the two numbers is %d\n", result );
break;
case 4: result = num1 / num2;
printf("The division of the two numbers is %d\n", result );
break;
default: printf("Wrong input!!!");
}
printf("\nDo you want to continue, y/n?\n");
scanf("%c", &answer);
while(answer == 'y');
}
return 0;
}

You have this code
char answer;
{
printf("\nWhat operation do you want to perform?\n");
//...
//... more code
//...
printf("\nDo you want to continue, y/n?\n");
scanf("%c", &answer);
while(answer == 'y');
}
Try to change it to:
char answer;
do {
printf("\nWhat operation do you want to perform?\n");
//...
//... more code
//...
printf("\nDo you want to continue, y/n?\n");
scanf("%c", &answer);
} while(answer == 'y');
So the basic form is:
do {
// code to repeat
} while (Boolean-expression);
BTW - You should always check the value returned by scanf
Example:
if (scanf("%c", &answer) != 1)
{
// Add error handling
}
Also notice that you often want a space before %c to remove any white space (including newlines) in the input stream. Like
if (scanf(" %c", &answer) != 1)
{
// Add error handling
}

Related

passing argument 1 and 2 of ‘strcmp’ makes pointer from integer without a cast [-Wint-conversion]

Hello so I've been working a little prgramme which is sort of a calculator (I'm a beginner) and well as you can see in the tittle at then end of the code, the two if strcmp doesn't work. And vscode is telling me (for the strcmp) Exception has occurred. Segmentation fault. But gcc is telling me what is in the tittle.
#include <stdio.h>
#include <string.h>
int main()
{
float num1;
float num2;
float anwser;
int rnum = 1;
int hi = 0;
char operator;
char ifyorn;
char y = 'y';
char n = 'n';
while (hi == 0)
{
printf("Enter operator +, -, /, x: ");
scanf(" %c", &operator);
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
switch (operator)
{
case '+':
anwser = num1 + num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '-':
anwser = num1 - num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case 'x':
anwser = num1 * num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '/':
anwser = num1 / num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
default:
printf("This is not a valid character please try again :(");
break;
}
if(strcmp (ifyorn, n) == 0)
{
printf("%f", anwser);
hi == 1;
}
if(strcmp (ifyorn, y) == 0)
{
hi == 0;
}
}
}
The variables ifyorn, y and n are declared having the type char.
char ifyorn;
char y = 'y';
char n = 'n';
The function strcmp expects arguments of the pointer type char * that point to strings.
So these if statements
if(strcmp (ifyorn, n) == 0)
and
if(strcmp (ifyorn, y) == 0)
are incorrect. Instead you should write
if ( ifyorn == n )
and
if ( ifyorn == y )
Also instead of assignments you are using the comparison operator in these statements
hi == 1;
and
hi == 0;
You need to write
hi = 1;
and
hi = 0;
Increasing the variable rnum looks senseless
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
Why not just to write
printf("Enter num %d :", 1 );
scanf("%f", &num1);
printf("Enter num %d :", 2 );
scanf("%f", &num2);
And in the code snippet under the label default you should add one more statement
default:
printf("This is not a valid character please try again :(");
ifyorn = y;
break;
You don't have to be mean to the guy ,he is learning.
You are getting this error because you are passing characters to strcmp() instead of pointers to characters.
Here is more information regarding that function.
https://www.programiz.com/c-programming/library-function/string.h/strcmp

Repeat the c program according to user

I want this program to repeat every time when users wants to continue.
I want user to choose "yes" to continue the program using other options but it's not executable. I used 'if else' statement for that but I am not getting any applicable or satisfying results. Can someone help me on this matter?
#include <stdio.h>
int main() {
float a, b;
int p;
char q;
printf("Enter the first number:");
scanf("%f", &a);
printf("Enter the second number:");
scanf("%f", &b);
printf("Choose the option:\n1.Sum\n \n2.Subtraction\n \n3.Multiplication\n \n4.Divison\n \nyour choice=");
scanf("%d", &p);
switch (p)
{
case 1:
printf("The sum of above numbers is: %f", a + b);
break;
case 2:
printf("The subtraction of above numbers is:%f", a - b);
break;
case 3:
printf("The multiplication of above numbers is:%f", a * b);
break;
case 4:
printf("The division of above numbers is:%f", a / b);
break;
}
printf("\n\nDo u want to continue:(y for yes and n for no) :");
scanf("%c", &q);
if (q == 'y')
return main();
else
return 0;
}
You need to use a loop for this. Explanations in the comments:
int main() {
float a, b;
int p;
char q;
do // use a loop here
{
printf("Enter the first number:");
scanf("%f", &a);
printf("Enter the second number:");
scanf("%f", &b);
printf("Choose the option:\n1.Sum\n \n2.Subtraction\n \n3.Multiplication\n \n4.Divison\n \nyour choice=");
scanf("%d", &p);
switch (p)
{
case 1:
printf("The sum of above numbers is: %f", a + b);
break;
case 2:
printf("The subtraction of above numbers is:%f", a - b);
break;
case 3:
printf("The multiplication of above numbers is:%f", a * b);
break;
case 4:
printf("The division of above numbers is:%f", a / b);
break;
}
printf("\n\nDo you want to continue: (y for yes and n for no) :");
scanf(" %c", &q); // use " %c" instead of "%c", the white space
// will absorb any blank space (including newlines)
} while (q == 'y'); // continue loop if user has entered 'y'
return 0;
}

How to make this program ask for input again if invalid input is entered (in C programming)? [duplicate]

This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 5 years ago.
There are two different spots where the check happens.
That is, where you enter a, s, m, d, or q and when you enter the first and second number.
At any of the checks, if the check is false, it should ask you to re-enter your input.
I'm guessing this can be done by putting a scanf statement for the numbers part inside a while loop check, but when I enter an invalid value (non-number) the loop runs infinitely.
So I must be doing something wrong. I have made the a, s, m, d, and q part work for the most part.
But the second part never seems to work. For this, I left my failed attempts at the while loops out, and instead in //comments.
Any help would be greatly appreciated!
Here is my code so far:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
float num1,num2,answer;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
while ((ch = getchar())!='q')
{
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
ch=tolower(ch);
if (ch=='\n')
continue;
else
{
switch(ch)
{
case 'a':
//The code below is what I have tried to make work.
//This code would also be copy pasted to the other cases,
//of course with the correct operations respectively being used.
//
//printf("Enter first number: ")
//while(scanf("%f",&num1)==0)
//{
// printf("Invalid input. Please enter a number.");
// scanf("%f",&num1);
//}
//printf("Enter second number: ")
//while(scanf("%f",&num2)==0)
//{
// printf("Invalid input. Please enter a number.");
// scanf("%f",&num2);
//}
//answer = num1 + num2;
//printf("%f + %f = %f\n",num1,num2,answer);
//break;
//
//I have also tried to make this work using do-while loops
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 + num2;
printf("%f + %f = %f\n",num1,num2,answer);
break;
case 's':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 - num2;
printf("%f - %f = %f\n",num1,num2,answer);
break;
case 'm':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 * num2;
printf("%f * %f = %f\n",num1,num2,answer);
break;
case 'd':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 / num2;
printf("%f / %f = %f\n",num1,num2,answer);
break;
default:
printf("That is not a valid operation.\n");
break;
}
}
}
return 0;
}
Again, thanks for any help!
Ya'll would be a life saver!
Cheers!
-Will S.
EDIT: I got my code to work! Here is the final code...
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
float num1,num2,answer;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
while ((ch = getchar())!='q')
{
ch=tolower(ch);
//Ignore whitespace
if (ch=='\n')
continue;
else
{
switch(ch)
{
//Addition part
case 'a':
//First number
printf("Enter first number: ");
//Check to see if input is a number
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Second number
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Do math for respective operation
answer = num1 + num2;
//Print out result
printf("%.3f + %.3f = %.3f\n", num1,num2,answer);
break;
//Subtraction part
case 's':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
answer = num1 - num2;
printf("%.3f - %.3f = %.3f\n", num1,num2,answer);
break;
//Multiplication part
case 'm':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
answer = num1 * num2;
printf("%.3f * %.3f = %.3f\n", num1,num2,answer);
break;
//Division part
case 'd':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Check for if number is a zero
while (num2==0)
{
printf("Please enter a non-zero number, such as 2.5, -1.78E8, or 3: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
}
answer = num1 / num2;
printf("%.3f / %.3f = %.3f\n", num1,num2,answer);
break;
//For if a non-valid operation is entered
default:
printf("That is not a valid operation.\n");
break;
}
}
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
}
printf("Bye.\n");
return 0;
}
Looking back at it, I probably could do without the if/else statement.
There are multiple problems with your code. First of all in this loop
You are taking input two times on failure
while(scanf("%f",&num1)==0) //Taking Input Here Once
{
printf("Invalid input. Please enter a number.");
scanf("%f",&num1); //Again Taking input.
}
Instead what you wanted was to check the return value of the scanf() and if it was 0 you would execute the loop again, so this would be the way to do that:
int l = 0;
while(l==0){ //Checking l, if it is zero or not, if zero running loop again.
printf("Invalid input. Please enter a number.");
l = scanf("%f",&num1); //Storing Return Value of scanf in l
}
When the program will encounter any line with scanf("%f" , &num1) or scanf("%f" , &num2), it will skip all the white spaces and wait for next input. In the case where the input does not match the format specification, then the input isn't consumed and remains in the input buffer.
int l = 0;
while(l==0){ //Checking l
printf("Invalid input. Please enter a number.");
l = scanf("%f",&num1); //scanf will look at the buffer if the input
//does not match, it will not be consumed
//and will remain in buffer.
}
In other words, the character that doesn't match is never read. So when you type e.g. an a character, your code will loop indefinitely as scanf continues to fail on the same character.
When the program executes its last scanf("%f",&num2) call then because of the enter there is a newline \n character present in buffer and so due to ch = getchar(), new line \n gets stored in ch and the following if condition satisfies and the loop execute again.
if(ch =='\n')
continue;
while(scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number.");
scanf("%f",&num1);
}
This loops scans two numbers per iteration. This is not what you want. Lose the second scanf.
You should also check for EOF and errors.
int result;
while((result = scanf("%f",&num1))==0)
{
printf("Invalid input. Please enter a number.");
}
if (result == EOF) .... report an error and exit ...

While loop - changing string variable

As a newbie to c programming (I've only had experience in visual basic), I'm not entirely sure how a while loop with a changing string variable in its condition statement should function.
The following code is a simple calculator that I was making that allows the user to input an operation and two numbers, then output the respective result. I'am trying to code in a while loop that continually repeats the procedure until the user decides to exit it. However it seems that the line scanf("%c", &quit); isn't affecting the while loop condition statement.
#include <stdio.h>
int main() {
float num1, num2;
char operation;
char quit = "n";
while (quit = "n"){
printf("Enter an operator (+, -, *, /) \n");
scanf(" %c", &operation);
printf("Enter the numbers you wish to carry out the operation on \n");
scanf("%f %f", &num1, &num2);
switch(operation) {
case '+':
printf("%f\n", num1+num2);
break;
case '-':
printf("%f\n", num1-num2);
break;
case '*':
printf("%f\n", num1*num2);
break;
case '/':
printf("%f\n", num1/num2);
break;
}
printf("Would you like quit the program, is so enter 'y' \n");
scanf("%c", &quit);
}
return 0;
}
Thanks for all your help in advance.
You could do like this
#include <stdio.h>
int main() {
float num1, num2;
char operation;
char quit = 'n';
//while (quit = "n") //
while (quit!= 'y')
{
printf("Enter an operator (+, -, *, /) \n");
scanf(" %c", &operation);
printf("Enter the numbers you wish to carry out the operation on \n");
scanf("%f %f", &num1, &num2);
switch(operation) {
case '+':
printf("%f\n", num1+num2);
break;
case '-':
printf("%f\n", num1-num2);
break;
case '*':
printf("%f\n", num1*num2);
break;
case '/':
printf("%f\n", num1/num2);
break;
}
printf("Would you like quit the program, is so enter 'y' \n");
scanf("%c", &quit);
}
return 0;
}
replace while (quit = "n") with while (quit! = 'y')
That's because you're assigning the value of the quit variable in your while loop, instead of checking for its value.
Use == for =
while(quit == "n"){...}

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