I'm trying to write a basic calculator program in C, and I'm almost there! I have one issue though, and it's concerning repeatedly querying the user for input.
I can get through my loop once, but even though the user inputs the correct character, my program still breaks out of the loop.
I'm fairly new to C, but I've done a decent amount of programming in Java, so I understand the functionality of loops, conditionals, and data types.
#include <stdio.h>
int main()
{
char yes;
int a, b, c, choice;
yes = 'y';
while(yes == 'y' || yes == 'Y')
{
printf("Enter first integer: ");
scanf("%d", &a);
printf("Enter second integer: ");
scanf("%d", &b);
printf("\nAdd(1), Subtract(2), Multiply(3), Divide(4): ");
scanf("%d", &choice);
printf("\n");
switch(choice)
{
case(1):
c = a + b;
printf("%d + %d = %d\n", a, b, c);
break;
case(2):
c = a - b;
printf("%d - %d = %d\n", a, b, c);
break;
case(3):
c = a * b;
printf("%d * %d = %d\n", a, b, c);
break;
case(4):
c = a / (float)b;
printf("%d / %d = %d\n", a, b, c);
break;
default:
printf("Incorrect choice. Try again.\n");
}
printf("\nAgain (Y/N): ");
scanf("%c", &yes);
}
return 0;
}
You need to consume the trailling newline, enter remains in the stdin buffer ready to be read by the next scanf.
Change
scanf("%c", &yes);
to
scanf(" %c", &yes);
The problem is that the newline character is left on the input after inputting a number to choose what operation to do. So when the user is asked if they want to do it again, the newline is taken instead of the y or n. I might be wrong, it's been a while since I've done some programming.
What worked for me to fix it was to put a little bit of code after the line
printf("\nAgain (Y/N): ");
Adding this bit right after the printf statement will remove the newline from the input and should do the trick.
while(getchar() != '\n')
getchar();
Maybe someone else can explain exactly why this works, I don't remember the specifics. It's a little thing that I found useful to remember, it comes up every now and again.
Related
So, in this link -> Problems doing a while loop I did a question about a problem dealing with the use of while instead of calling main(), and it helped me, my code worked, but there's a new little problem. I'mma show it with a kind of "Dice Roller Code"
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
srand((unsigned)time(NULL));
int totalSides, dice, modifier;
char c, d;
printf("Welcome to the dice roller!\n");
printf("If you wanna roll the dice, press 'r'. If you wanna quit, press 'q': ");
scanf(" %c", &c);
while(c == 'r'){
printf("How many sides does the dice you want to roll have? Answer with a int number: ");
scanf("%d", &totalSides);
printf("Do you need any modifier? Press 'a' to add, press any other key to dispense: ");
scanf(" %c", &d);
if(d == 'a'){
printf("Insert your modifier value: ");
scanf("%d", &modifier);
printf("\n");
}
dice = rand() % totalSides + 1;
printf("You've got a %d!\n", dice);
if(d == 'a'){
printf("But you've got a %d modifier...\n", modifier);
dice = dice + modifier;
printf("Then, you got a %d!", dice);
}
printf("\n\n\n\n");
repeat();
c = repeat();
printf("\n\n\n\n");
}
}
int repeat(){
char c;
printf("Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: ");
scanf("%c", &c);
return c;
}
The program works very well, but in the output I got the same sentence two times, like:
"Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: "
How can I solve this?
You are calling repeat twice, so therefore it is printing twice.
repeat();
c = repeat();
Try replacing the first call to repeat to getchar(). This will consume the character entered after the modifer line.
getchar();
c = repeat();
It looks like you are just starting to learn C, and it might be worthwhile to read a book on the matter. One that I can recommend is Modern C. It's available free online, or you can buy a print version.
The problem is, basically, that if user enters a:5, b:f, everything works fine. But if it's the other way around and enters a letter to the 'a' variable, the program ends saying "Incorrect input", not letting the user to finish typing in rest of the variables. Why? Is it because of how I dealt with checking if the input is correct in the first place? How to "delay" the message and make it show after user finishes entering variables?
Here's the code:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
As Weather Vane already pointed out, the reason the program exits is, that when you enter a character (%c) and the scanf function is waiting for a integer (%d) it ignores the char, doesn't find an int but ends its' search on the '\n' (enter), so your variable l1 stays 0. This happens for all of your scanf calls, as it doesn't clear the buffer from characters that don't match.
Solving this
You can clear the input buffer, so that all the other scanf calls can get an actual input, though, you are still going to get an "Incorrect input" at the end.
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
printf("Number b: ");
l2 = scanf("%d", &b);
while (getchar() != '\n');
If you want to repeat the input process until a user enters the numbers correctly, you have to check the return value of the scanf in a while loop, something like this:
do {
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
} while (l1 != 1 || l1 != EOF);
Try this:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
getchar();
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
Reference : scanf() leaves the new line char in the buffer
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'm struggling with what seems a trivial problem in C inputting data from the keyboard, but I'm a C noob (with some background in Java, though)
What I need: I need to type an int value from the keyboard (then press Enter), then I need the user to press Enter only without inputting anything, and then to type another int (and press Enter one more time).
What I can do:
int a = 0;
int b = 0;
scanf("%d", &a);
skip_line_cool_function();
scanf("%d", &b);
printf("You have just entered: &d and &d", a, b);
As you can see, I don't know how to skip the line.
What I have tried: scanf entering a dummy C-string, but, as you know, when you enter nothing, it patiently waits for at least something to be entered.
What I Googled: I suspect that fgets can do the job, but honestly, I didn't understand how to use it in my case.
/* Read first integer */
do {
if(!fgets(buffer, sizeof buffer, stdin)) break;
} while( last_character_of(buffer) != '\n');
/* Read next integer */
If you are this much rigid about the UI that the user will only press a single enter then why not do this?
int a = 0;
int b = 0;
scanf("%d", &a);
getchar(); /* this will get the enter pressed after entering a */
getchar(); /* this will get the enter for the blank line */
scanf("%d", &b);
printf("You have just entered: &d and &b", a, b);
Also the code snippet you've posted will result into compile error. printf() will need integer format specifier %d to work properly. Use this:
printf("You have just entered: %d and %d", a, b);
I can't see why does the While loop just speed away and skipping the scanf for the char?
It would not even ask for my input and just loop like there's no tomorrow.
#include <stdio.h>
int main()
{
int number;
int multiply, ans;
char choice;
printf("-------------------------------------");
printf("\n MULTIPLICATION TABLE ");
printf("\n-------------------------------------");
do
{
printf("\nEnter an integer number:");
scanf("%d", &number);
printf("\nMultiplication of %d is :-\n", number);
printf("\n");
for(multiply=1; multiply<11; multiply++){
ans = number * multiply;
printf(" %d", ans);
}
printf("\n");
printf("\nWould you like to continue? [Y] for Yes,[N] for no : ");
scanf("%c", &choice);
printf("\n");
}
while(choice='Y');
printf("Thank You");
return 0;
}
scanf() doesn't do what you think it does (newline characters, buffering, etc.). It's preferred to use fgetc():
choice = fgetc(stdin);
For the same reason, you need to get rid of the trailing newline that
scanf("%d", &number");
leaves in the standard input buffer. To fix this, insert
fgetc(stdin);
after that particular call to scanf().
Also, C is not Pascal. The equality comparison operator - and the condition - you're looking for is
while (choice == 'Y')
the single equation mark denotes an assignment.
I think you need to use == operator for the comparison in while condition check as:
while(choice=='Y');
Currently you are using = operator, which is assigning Y to choice variable.
It has been a long time since I programmed in that language, but at a glance, you have:
while(choice='Y');
instead of:
while(choice=='Y');
== compares, = sets equal to. So the while loop is actually not checking the condition you're trying to set.