I'm using a do-while loop to print a menu to the screen. And I'm reading choice as an integer. The proplem is that if the user enter a character the program blows up. How can I avoid that?
#include <stdio.h>
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
scanf("%d", &choice);
return choice;
}
int main() {
int choice;
do {
choice = menu();
if (choice != 4) {
if (choice == 1)
//lab5(choice);
else if (choice == 2)
//lab10(choice);
else if (choice == 3)
// lab11(choice);
else
printf("invalid choice\n");
}
} while (choice != 4);
return 0;
}
This should work for you, you need to check the return value of scanf
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
if(scanf("%d", &choice) == 1)
{
return choice;
}
else
{
return 0;
}
}
The scanf() (and family of functions) returns the number of successful conversions from the input buffer, if the conversion (%d) fails the function returns 0 (or EOF). In this case the character that could not be converted is not removed from buffer, this is why the endless loop occur, the conversion keeps failing for ever.
I used this method to flush the input buffer after the scanf call and the program behaved as expected.
Run the program online (don't know for how long this will stay up)
void flushInput(){
int c;
while((c = getchar()) != EOF && c != '\n')
/* discard */ ;
}
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
if(scanf("%d", &choice) != 1){
flushInput();
return 0;
}else{
flushInput();
return choice;
}
}
/*USE This Code*/
#include <stdio.h>
#include <stdlib.h>
void orderAsk(int orderStorage[1]);
int main()
{
int orderStorage[1];
orderAsk(orderStorage);
printf("%d",orderStorage[0]);
return 0;
}
void orderAsk(int orderStorage[1]){
int d;
d = scanf("%d", &orderStorage[0]);
if ( d!= 1) {
system("cls");
fflush(stdin);
printf("Error! Re-Enter\n");
orderAsk(orderStorage);
}
}
Related
When I enter a non-integer value it cause an infinite loop. Do I need to replace scanf? If so how can I do that.
int num=1;
if(num==1){
int slct;
printf("\n\tWelcome");
printf("\n1. Login\n2. Register\n3. Account\n4. Exit\n");
SELECTION: ;
printf("\n\tEnter a number:");
scanf("%d",&slct);
if (slct == 1){}
else if (slct == 2){}
else if (slct == 3){}
else if (slct == 4){
return 0;
} else {
goto SELECTION;
}
}
You need to check the return value of scanf and flush the input:
#include <stdbool.h>
#include <stdio.h>
int main()
{
bool done = false;
while (!done) {
printf("\n\tWelcome\n");
printf("1. Login\n");
printf("2. Register\n");
printf("3. Account\n");
printf("4. Exit\n\n");
printf("Enter a number:");
int selection;
int result = scanf("%d", &selection);
if (EOF == result) {
done = true;
}
else if (1 != result) {
printf("You did not enter a valid number\n");
int c;
while ((c = getchar()) != '\n' && c != EOF) {}
done = (c == EOF);
}
else if (1 == selection) {
printf("You chose login\n");
}
else if (2 == selection) {
printf("You chose register\n");
}
else if (3 == selection) {
printf("You chose account\n");
}
else if (4 == selection) {
done = true;
}
else {
printf("Please pick a number between 1 and 4\n");
}
}
}
The format string in scanf("%d",&slct); is %d which means you want to read a number.
When you enter something else than a number, scanf returns 0 to indicate that zero numbers were read.
If the scanf encounters and end-of-file when attempting to read the input (enter control-D) then it returns the special value EOF.
Also, scanf does not consume the incorrect input, so you need to explicitly flush it.
This question already has answers here:
Validate the type of input in a do-while loop
(5 answers)
While-loop ignores scanf the second time
(3 answers)
Closed 4 years ago.
printf("Enter an integer: ");
status = scanf("%d", &integer);
if (status == 0){
do{
printf("Please enter an integer: ");
status = scanf("%d", &integer);
}
while (status == 0);
}
I'm trying to prevent a user from entering a data of type of character. However, after the prompt, "Please enter an integer: ", it doesn't wait for an input. Hence, it goes into an infinite loop whenever I enter a letter at the first prompt. How do I fix this? Any heeelp will be greatly appreciated!
You need clean the buffer first, you can use fflush(stdin); like this:
int integer, status=0;
if (status == 0)
{
do
{
printf("\nPlease enter an integer: ");
status = scanf("%d", &integer);
fflush(stdin);
}
while (status == 0);
}
It's not in standard C using fflush(stdin) but you can clean the buffer in other ways.
You can build your own function to clean the buffer, like this:
void flushKeyBoard()
{
int ch; //variable to read data into
while((ch = getc(stdin)) != EOF && ch != '\n');
}
To clean the screen call this function:
void clrscr()
{
system("#cls||clear");
}
Final code:
#include <stdio.h>
void clrscr()
{
system("#cls||clear");
}
void flushKeyBoard()
{
int ch; //variable to read data into
while((ch = getc(stdin)) != EOF && ch != '\n');
}
int main()
{
int integer, status=0;
if (status == 0)
{
do
{
printf("\nPlease enter an integer: ");
status = scanf("%d", &integer);
flushKeyBoard();
clrscr();
}
while (status==0);
}
}
your %integer, should be declared int.
Like that:
int integer;
printf("Please input an integer value: ");
scanf("%d", &integer);
#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf(" %d", &i) > 0) // step-2
printf("Num=%d\n", i);
else
printf("Entered character.Pls enter int\n");
}
}
I want to continue the scan again if user entered a value other than integer when I run the above code with a char input it is running infinite loop. Please suggest why or any solution ...?
#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf_s(" %d", &i) > 0) { // step-2
printf("Num=%d\n", i);
break;
}
else {
printf("Entered character.Pls enter int\n");
fseek(stdin, 0, SEEK_END);
}
}
}
If you enter a character say a for the above program it will not match with %d so it will remain in the buffer. The next time in the loop, it will again not match %d and you will enter an infinite loop.
What you can do, is read from the buffer until you encounter a newline character. The second loop will remove any characters until and including the newline character.
#include <stdio.h>
int main() {
int i;
char dummy;
while (1) {
printf("Enter no?\n"); // step -1
scanf(" %d", &i)
if (i > 0) // step-2
printf("Num=%d\n", i);
else
printf("Entered character.Pls enter int\n");
do{
scanf("%c",&dummy);
}while (dummy != '\n'); // Add this loop
}
}
I am trying to check if the user inputs y or something else.
I have tried creating a string and looping through what the user inputs, but that doesn't work.
char answer[] = "n";
for(int i = 0; i < sizeof(answer)/4; i++) {
if(answer[i] == "y") {
calculatorPrompt();
} else if(answer[i] === "n") {
printf("Okay, bye!");
System(100);
}
}
This is my code (I'm sure it crashes on the if statement):
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%s", answer);
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
calculatorPrompt() function:
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d\n", a) != 1) {
checkNumber();
} else {
printf("Enter your second number: ");
if(scanf("%d\n", b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
}
}
calculate() function:
int calculate(int a, int b) {
return a + b;
}
checkNumber() function:
void checkNumber() {
printf("Really? You didn't enter a number... Now exiting..");
return;
}
I have included <windows.h> <stdio.h> and <stdbool.h>
I'm also confused as to why it crashes.
The return value of the program is -1,073,741,819.
You have multiple issues with scanf() statements in the code :
in calculatorPrompt() funtion of your code, you use :
if(scanf("%d\n", a) != 1) //wrong : sending variable as argument
This is wrong because you need to send address of the variable as the argument not the variable itself as argument.
if(scanf("%d", &a) != 1) //correct : sending address as argument
similarly change while scanning other integers in the code.
here,
char answer = 'n';
scanf("%s", answer);
As you are using the wrong format specifier, this invokes Undefined behavior.
here since answer is a char so, instead use :
scanf(" %c", &answer); //space to avoid white spaces
and as I've already suggested in the comments :
You use i < sizeof(answer)/4 in the for loop
No! it must be i < sizeof(answer), as in a string every element occupies only 1 byte not 4 (you are mistaking it for an int array)
by the way you don't have any strings in your code
I don't recommend the code you have written for calculator, yet wanted to help you find the working code. Try following code that is based on your own code. Hope you'll see the differences and understand the reasons why the program was crashing in your case.
#include <Windows.h>
#include <stdio.h>
#include <stdbool.h>
bool checkNumber(int num)
{
return true;
}
int calculate(int a, int b) {
return a + b;
}
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
scanf_s("%d", &a);
if (checkNumber(a)) {
}
printf("Enter your second number: ");
scanf_s("%d", &b);
if (checkNumber(b)) {
}
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
int main()
{
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf_s("%c", &answer);
if (answer == 'y') {
calculatorPrompt();
}
else if (answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
}
#include <windows.h>
#include <stdio.h>
#include <stdbool.h>
void calculatorPrompt(void);
int main(void){
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%c", &answer);//scanf need address of store place
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!\n");
Sleep(100); //wait for 100 milliseconds
}
return 0;
}
void checkNumber(void);
int calculate(int a, int b);
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d", &a) != 1) {//\n : skip white spaces and wait input not spaces
checkNumber();//call when invalid input
} else {
printf("Enter your second number: ");
if(scanf("%d", &b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d\n", sum);
}
}
}
void checkNumber(void){//output message and clear input.
fprintf(stderr, "invalid input!\n");
scanf("%*[^\n]%*c");//clear upto end of line.
}
int calculate(int a, int b) {
return a + b;
}
When you scan a character , you just need to use %c. If you are planning to continue with string you must use strcmp() for comparison not ==.
I am a beginner in C...
I have made a made a calculator type program which uses four basic functions in C using if-else loop.
I want when the program comes to end(after the user has added, subtracted etc. etc. then there is a option "Y/N" so that the program can be restarted???"
Here is the sample of the code
#include<stdio.h>
int main()
{
int choi;
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==4)
{
float a=0,b=0,c=0;
printf("\nEnter Divident :");
scanf("%d",&a);
printf("\nEnter the Divisor :");
scanf("%d", &b);
c=a/b;
printf("\nThe Quotient is : %d\n\n",c);
char choice;
printf("Do you want to try it again?(Y/N) ");
scanf("%c", &choice);
// I want a code here so that the program can be restarted
getch();
return 0;
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2 or 3 !\n\n");
}
end:
getch();
return 0;
}
The best way would be to do some sort of a while loop.
int goAgain=1;
while (goAgain==1) {
... //Normal code here
printf("Again?")
scanf("%c",&again)
if (again=='N') {
goAgain=0;
}
}
Or you could use a do-while loop as well
do {
... //Normal code here
printf("Again?")
scanf("%c",&again)
} while (again=='Y')
Basically, this will keep looping over the bit of code over and over until the person types N to end it.
A do-while loop would be most suitable for this purpose.
int main() {
char choice;
do {
// Calculator stuff here...
printf("Do you want to try it again? (Y/N) ");
scanf("%c", &choice);
} while (choice == 'Y');
}
Edit: As it turns out, there is another problem with the program above, which is that scanf() reads a character but leaves a Newline character in the buffer. Therefore, if the user types YEnter, the program will repeat once (choice == 'Y' the first time), then exit (choice == '\n' the second time).
It is therefore necessary to keep reading until the Newline has been consumed.
int main() {
char choice;
do {
// Calculator stuff here...
printf("Do you want to try it again? (Y/N) ");
choice = getchar();
while (choice != '\n' && getchar() != '\n') {};
} while (choice == 'Y' || choice == 'y');
}
char continue = 'Y'
while (continue == 'Y') {
... //Normal code here
printf("Again?")
scanf("%c",&continue)
}
you can try like this, avoid go to
#include<stdio.h>
int main()
{
int choi;
while(true)
{
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\n5. Exit");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==1)
{
}
else if(choi==2)
{
}
else if(choi==3)
{
}
else if(choi==4)
{
}
else if(choi==5)
{
return 0; //exit(0);
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2,3,4 or 5 !\n\n");
}
}
return 0;
}
By using do-while loop, which is generally used for menu-driven programs.
#include<stdio.h>
int main()
{
int choi;
char choice;
do{
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==4)
{
float a=0,b=0,c=0;
printf("\nEnter Divident :");
scanf("%d",&a);
printf("\nEnter the Divisor :");
scanf("%d", &b);
c=a/b;
printf("\nThe Quotient is : %d\n\n",c);
char choice;
printf("Do you want to try it again?(Y/N) ");
scanf("%c", &choice);
// I want a code here so that the program can be restarted
getch();
return 0;
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2 or 3 !\n\n");
}
printf("Want to continue (y/n)?");
scanf("%d", &choice); // Enter the character
}while (choice == 'y' || choice == 'Y');
end:
getch();
return 0;
P.S.: I would suggest you to use switch case, instead of if-else statements to do the job.
You can also use a goto:
int main() {
...
if (c=='y') {
main();
} else {
goto end;
}
end:
...
}