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"){...}
Related
I am working on an accumulator that asks for different inputs and based on those inputs, updates values in an accumulator. My loop however, doesn't seem to run when I ask for a decimal, hexadecimal, or octal to be inputed. Could someone possibly take a look and give some suggestions to fix it? Thank you! Also Im suppose to somehow use a while loop in my print_menu() function that will check is the input is valid. Any suggestions?
#include <stdio.h>
#include <string.h>
short get_operand(char mode);
void print_acc(short acc);
char print_menu(void);
int main(void);
int main(){
char mode = 'D';
short acc = 8;
char input[10];
char option;
char valid_input[7] = "OHDCSQ";
while (mode != 'Q'){
print_acc(acc);
print_menu();
scanf("%s", &input);
printf("%s\n", input);
option = (char) toupper(input[0]);
switch(option){
case 'O':
mode = 'O';
printf("mode\n");
printf("Mode is Octal\n");
break;
case 'H':
mode = 'H';
printf("Mode is Hexadecimal\n");
break;
case 'D':
mode = 'D';
printf("Mode is Decimal\n");
break;
case 'C':
acc = 0;
break;
case 'S':
get_operand(mode);
if (mode == 'H'){
scanf("%hx", &acc);
printf("%hx", acc);
print_acc(acc);
}
else if (mode == 'O'){
scanf("%ho", &acc);
printf("%ho", acc);
print_acc(acc);
}
else{
scanf("%hd", &acc);
printf("%hd", acc);
print_acc(acc);
}
case 'Q':
mode = 'Q';
printf("\n");
break;
}
//return acc;
}
}
void print_acc(short acc){
printf("\n");
printf("****************************************\n");
printf("* Accumulator: *\n");
printf("* Hex : %04hx *\n", acc);
printf("* Octal : %08ho *\n", acc);
printf("* Decimal : %06hd *\n", acc);
printf("****************************************\n");
}
char print_menu(void){
printf("\n");
printf("Please Select one of the following options:\n");
printf("O Octal Mode\n");
printf("H Hecadecimal Mode\n");
printf("D Decimal Mode\n");
printf("\n");
printf("C Clear Accumulator\n");
printf("S Set Accumulator\n");
printf("\n");
printf("Q Quit\n");
printf("\n");
printf("Option: ");
}
short get_operand(char mode){
switch(mode){
case 'H':
printf("Enter Hex value:");
break;
case 'O':
printf("Enter Octal value:");
break;
default:
printf("Enter decimal value: ");
break;
}
return mode;
}
In the 'S' case where you read in a number, you forget to add a break statement at the end of the case. This results in the code falling through to the Q case which causes the loop to exit.
Add the break and the loop will continue as expected:
case 'S':
...
break;
case 'Q':
...
This is also incorrect:
scanf("%s", &input);
%s expects a char *, but you're passing the address of an array (a char (*)[10] to be presice). Pass in the array directly, which will decay to a pointer to the first element to yield the correct type:
scanf("%s", input);
Also, change print_menu and get_operand to return void, since you're not using the return value and in the former case failing to include one.
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
}
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.
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
}
I wrote below code:
#include<stdio.h>
int main() {
char o,r;
int x,y;
do {
printf("Enter operator: '+' or '-' or '*' or '/'\n");
scanf("%c",&o);
printf("Enter first number: ");
scanf("%d",&x);
printf("Enter second number: ");
scanf("%d",&y);
switch(o) {
case '+':
printf("Sum: %d",x+y);
break;
case '-':
printf("Subtract: %d",x-y);
break;
case '*':
printf("Multiply: %d",x*y);
break;
case '/':
printf("Division: %d",x/y);
break;
default:
printf("Wrong operator entered.");
}
printf("\nEnter y or Y to continue: ");
scanf("%c",&r); // r is not getting value?. why?
} while((r=='y')||(r=='Y'));
}
r is not getting value thus it is not doing what it supposed to do.
printf("\nEnter y or Y to continue: ");
scanf("%c",&r);
What seems to be the problem? Am I missing something?
Why does this code work fine in c++ if I use cin, but it fails when I use scanf in c?
You need to add the line (or something similar):
while(getchar() != '\n');
After you enter the second number, '\n', the newline character, is left in stdin and is being placed in r.
You can prove this by adding the following lines after the while loop:
if(r == '\n')
printf("\nnewline\n");
Enter operator: '+' or '-' or '*' or '/'
*
Enter first number: 5
Enter second number: 6
Multiply: 30
Enter y or Y to continue:
newline
check the below
#include<stdio.h>
int main()
{
char o,r;
int x,y;
do{
printf("Enter operator: '+' or '-' or '*' or '/'\n");
scanf(" %c",&o);
printf("Enter first number: ");
scanf("%d",&x);
printf("Enter second number: ");
scanf("%d",&y);
switch(o)
{
case '+':
printf("Sum: %d",x+y);
break;
case '-':
printf("Subtract: %d",x-y);
break;
case '*':
printf("Multiply: %d",x*y);
break;
case '/':
printf("Division: %d",x/y);
break;
default:
printf("Wrong operator entered.");
}
printf("\nEnter y or Y to continue: ");
scanf(" %c",&r);
} while((r=='y')||(r=='Y'));
}