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.
Related
Just started learning C and tried to make a calculator to test myself. I thought it would be a fun challenge to make it so:
the program prints an error message to the user if the input(s) is not a number
the user can input a number again, without shutting down the program
What I've learned in C so far is:
printf, scanf
data types
if statements
loops
functions
My question is, is it possible to accomplish the task with the knowledge mentioned above. If it is, what is that solution? (I've been stuck on this for quite a while now, so I hope me giving up on doing it myself is acceptable). If it's not, what do I need to learn to be able to do it?
Here's my code
#include <stdio.h>
float num1;
float num2;
float answer;
char operation;
int isNumber; //1 means true, 0 means false
char restart;
int main ()
{
printf ("Please enter the first number: ");
isNumber = scanf("%f", &num1);
while (isNumber == 0)
{
printf("Please enter a valid number: ");
isNumber = scanf("%f", &num1);
}
//This just keeps reapeating the printf message.
//Also, I just wrote the code for the first input.
//If it doesn't work for this one, no point in writing it for other inputs.
printf ("Please enter an operation: ");
scanf (" %c", &operation);
printf ("Please enter the second number: ");
scanf ("%f", &num2);
if (operation == '+')
{
answer = num1 + num2;
}
else if (operation == '-')
{
answer = num1 - num2;
}
else if (operation == '*')
{
answer = num1 * num2;
}
else if (operation == '/')
{
while (num2 == 0)
{
printf ("Cannot divide by 0. ");
printf ("Please enter another number\n");
scanf ("%f", &num2);
}
answer = num1 / num2;
}
printf ("\nThe answer is: %f", answer);
printf ("\n\nEnter 1 to do another calculation. Enter anything else to quit: ");
scanf(" %c", &restart);
if(restart == '1')
main();
else
return 0;
}
scanf() only reads input that matches the format specifier (in your case this is %f). Characters that do not match the format specifier causes scanf() to stop scanning and causes scanf() to leave the invalid characters in the stdin buffer.
In your while loop if a invalid character is entered it will get stuck in the stdin buffer. This invalid character will then get read by the next scanf() call in the loop, which will also leave it in the stdin buffer. This will continue, again and again, resulting in an infinite loop.
As you might be able to tell scanf() is a unreliable and quick - yet not very robust way to take input.
To fix it you could use a hacky solution like this:
while ((scanf("%f", &num1)) != 1)
{
printf("Please enter a valid number: ");
int c;
while((c = getchar()) != '\n' && c != EOF);
}
// while loop "eats up" any characters
// that scanf has left in stdin buffer
Instead of scanf() i reccomend you get familiar with a function such as fgets() to take input. Then you can use a function like sscanf() to parse the input to see if it is a float.
As a beginner, while you are learning C, it is fine to use scanf(). But as you delve deeper into C and write more complicated pieces of software you must consider using safer and more robust alternatives to unreliable functions like scanf().
To well handle user input, consider dropping all scanf() calls. To read a line of user input, use fgets().
How to check for non-number inputs
Create a helper function.
Read a line of text into a buffer and parse with sscanf() or strod(). sscanf() is OK and used below. strod() is better, yet some corner cases are beyond what a learner may appreciate.
#define LINE_LENGTH_MAX 400
// Return 1 on success, EOF on end-of-file, 0 on failure
int read_double(double *dest, const char *prompt) {
if (prompt) {
fputs(prompt, stdout);
}
char buffer[LINE_LENGTH_MAX + 1];
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
return EOF;
}
int n = 0;
sscanf(buffer, "%f %n", dest, &n);
if (n == 0) {
// Scanning failed
return 0;
}
if (dest[n]) {
// Yet there was extra junk at the end
return 0;
}
return 1;
}
More advance code would used strtod() and detect lines longer than LINE_LENGTH_MAX.
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 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.
#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;;
}
This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 8 years ago.
#include "stdio.h"
int main(void)
{
int order, nextp, N=3;
char cont;
nextp = 0;
printf("\nShould we continue (y or n): ");
scanf("%c", &cont);
if (cont != 'y') return;
for(; nextp < N; nextp++)
{
printf("Enter order number: ");
scanf("%d", &order);
printf("you have entered %d\n", order);
printf("okay now continue with cont\n");
printf("enter cont y or n: ");
scanf("%c", &cont);
if (cont != 'y')
{
printf("\nnot equal to y\n");
break;
}
printf("after intepreting t[0]");
}
return 0;
}
The output looks like this
Should we continue (y or n): y
Enter order number: 45
you have entered 45
okay now continue with cont
enter cont y or n:
not equal to y
The second input was skipped. Why?
because of newline character already in stdin , this is happening.
use
scanf(" %c", &cont);
instead of
scanf("%c", &cont);
note one space before %c.
After scanf("%d", &order); consumes the number (45 in this case), there is still a newline left after that. You can use scanf("%d\n", &order) to make it consume the return.
Another answer to this can be found here:
scanf() leaves the new line char in buffer?
This is why scanf is not typically preferred for character input. There's a left over carriage return after the previous input.
For example, if you were to add a getchar() after the order input, your problem would be solved, but that's not clean code. You can also see this explicitly by subsituting cont != 'y' to cont != '\n'.
Instead, use getchar() for all your input and check for \n
For most conversions scanf will skip whitespace, but for char format ("%c") you must skip white space by using an explicit space in the format (" %c") as explained here:
C - trying to read a single char
This is also explained in the scanf documentation, but it's confusing and may be better to use something else as others have mentioned.
You can use fflush()
printf("enter cont y or n: ");
fflush(stdin);
scanf("%c", &cont);