When I'm trying to run without debugging the code everything runs smooth but as soon as I press Y so I can continue inputting numbers it terminates (gotta say I need help)
int main() {
int a;
char c;
do {
puts("dwse mou enan arithmo: ");
scanf_s("%d", &a);
if (a > 0) {
if (a % 2 == 0)
printf("the number %d is even \n", a);
else
printf("the number %d is odd \n", a);
} else {
printf("the program won't run with negative numbers \n");
}
printf("if you want to proceed press y or Y :");
c = getchar();
getchar();
} while (c == 'y' || c == 'Y');
return 0;
}
The character read by getchar() is the pending newline that was typed after the number but was not consumed by scanf_s.
You should consume this pending newline before reading the next character for the continuation test, which can be done easily in scanf with a space before the %c conversion specification:
#include <stdio.h>
int main() {
int a;
char c;
for (;;) {
printf("dwse mou enan arithmo: ");
if (scanf_s("%d", &a) != 1)
break;
if (a >= 0) {
if (a % 2 == 0)
printf("the number %d is even\n", a);
else
printf("the number %d is odd\n", a);
} else {
printf("the program does not accept negative numbers\n");
}
printf("if you want to proceed press y or Y: ");
if (scanf_s(" %c", &c) != 1 || (c != 'y' && c != 'Y'))
break;
}
return 0;
}
Related
My code is below. I am using C language. I want to repeat the action from the start if the user types Y but I am confused how can I make that happen.
I tried to look for a solution but the results doesn't fit for my program.
#include <stdio.h>
int main() {
int A, B;
char Y, N, C;
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2: ");
scanf ("%i", &A);
printf ("= %i", A + B);
printf ("\n\nAdd again? Y or N\n");
scanf ("%c", &C);
if (C == Y) {
//This should contain the code that will repeat the:
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2:
} else if (C == N)
printf ("PROGRAM USE ENDED.");
else
printf ("Error.");
}
You should just wrap your code inside a for loop:
#include <stdio.h>
int main() {
int A, B;
char Y = 'Y', N = 'N', C;
for (;;) { // same as while(1)
printf("Enter value 1: ");
if (scanf("%i", &B) != 1)
break;
printf("\nEnter value 2: ");
if (scanf("%i", &A) != 1)
break;
printf("%i + %i = %i\n", A, B, A + B);
printf("\n\nAdd again? Y or N\n");
// note the initial space to skip the pending newline and other whitespace
if (scanf(" %c", &C) != 1 || C != Y)
break;
}
printf("PROGRAM USE ENDED.\n");
return 0;
}
There are a lot of errors in your program.
Syntax error: please resolve it on your own.
There is no need for Y and N to be declared as character, you can use them directly as they are not storing any value.
NOW, there is no need for continue you can use while loop.
I have resolved your problem. Please take a look
Also, you are using a lot of scanf so there is an input buffer, a simple solution to it is using getchar() which consumes the enter key spaces.
#include <stdio.h>
int main()
{
int A, B;
char C = 'Y';
while (C == 'Y')
{
printf("Enter value 1: ");
scanf("%i", &B);
printf("\nEnter value 2");
scanf("%i", &A);
printf("= %i\n", A + B);
getchar();
printf("\n\nAdd again? Y or N\n");
scanf("%c", &C);
}
if (C == 'N')
{
printf("PROGRAM USE ENDED.");
}
else
{
printf("Error.");
}
}
i tried to make a calculator but could the compiler is checking my if conditions properly.
here is my code,
i could not figure out how to solve this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("to add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c",&mode);
printf("%d %d %s \n",first,sec,mode);
if (mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == "s")
{
printf("%d \n",first-sec);
}
else if (mode == "m")
{
printf("%d \n",first*sec);
}
else if (mode == "d")
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}
void def(char name[],int age)
{
printf("het ur a %s and yo age is %i \n",name,age);
}
first attempt tried using a string instead of character (failed )
second attempt tried using a character but failed though!!
For comparing a single character in c, you must use single quotes. Consider an array of characters array[4] = {'c','a','r','\0'};
if(array[0] == 'c'){
//...
}
Comparing with double quotes, make the value inside it a string. For comparing strings you should #include <strings.h> and use the strcmp function.
There are two problems
mode == "s" mode is a char so just use mode == 's' and do the same for others also.
printf("%d %d %s \n",first,sec,mode); should be printf("%d %d %c \n",first,sec,mode);
you are using %s for printing a char
In your code "s" is a string not a caracter,to get a caracter you should write like this: 's'
here is the correction of your code :
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("\nMenu : \n");
printf("\nto add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c", &mode);
printf("%d %d %c \n",first,sec,mode);
if(mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == 's')
{
printf("%d \n",first-sec);
}
else if (mode == 'm')
{
printf("%d \n",first*sec);
}
else if (mode == 'd')
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}
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
So basically after the calculation the program prompts the user if they want to quit the program and the user inputs a character ('y' or 'n') and if the user puts a number or letter that is not 'y' or 'n' then the program will keep prompting the user until they input one of the characters.
The issue I'm running into is that the program will keep looping and prompting the user even if 'y' or 'n' is inputted. When I try fflush(stdin) it still doesn't work
I want to know how to loop the statement again if the user does not input one of the options and when they do input it properly, how to get the code inside the "do while" loop to repeat. Preferably without having to copy and paste the whole bloc again.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");
scanf("%f", &x);
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
scanf("%f", &t);
}
fflush(stdin);
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
scanf() will not throw away the newline character '\n' in the input buffer unless your format string is set to discard it. In your code, after entering input for your floats and pressing Enter, the newline is still in the buffer. So for the code that prompts Y\N, use this format string to ignore the newline
scanf(" %c",&d);
You can remove the fflush() calls if you do that. In your case, it looks like your loop conditionals are wrong though.
This line
while (d != 'y' || d != 'n')
is wrong.
Think of it like this:
The loop runs if d is NOT 'y' OR d is NOT 'n'
Now imagine you put in 'y'
d is 'y'. The loop runs if d is NOT 'y' OR d is NOT 'n'. Is d != 'y'? No. Is d != 'n'? Yes. Therefore the loop must run.
You need to use &&
while (d != 'y' && d != 'n')
Also, scanf doesn't throw away the newline so add a space for all your scanfs.
scanf("%c", &d); //change to scanf(" %c", &d);
Look in this part-
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
you are using whiletwice, i think you will wish to have a single while condition over here.. also if you are terminating while, then be sure there is a doinvolved.
Here is code which I think is right since you have many problems so i just have changed a lot :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");//delete the repeat scanf
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
}
fflush(stdin);
sum=0;//no initalization
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while ((d != 'y' )&& (d != 'n'))//this logical expression is the right way
{
scanf("%c", &d);
fflush(stdin);
printf("\n****************************************");//I change the pos of print to avoid double printing
printf("\nDo you wish to quit? (y/n): ");
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
ps:for your calculate part of cos I'm not sure about the correctness while runing:)
I am trying to make a simple calculator in Turbo C(I have my own reasons to why I use Turbo C now)
#include <stdio.h>
#define P printf
int loop[] = {1, 1, 1, 1};
int num;
char input[64];
void main()
{
int num1, num2;
char x, y;
while(loop[0] == 1)
{
clrscr();
P("Hello!, This simple calculator will help you compute 2 numbers.");
P("\nPress the corresponding key to choose the operation you will use.");
P("\n\nA - (A)ddition");
P("\nS - (S)ubtraction");
P("\nM - (M)ultiplication");
P("\nD - (D)ivision");
P("\n\nAnswer: ");
while(loop[1] == 1)
{
x = getchar();
if(tolower(x) == 'a')
{
P("\nYou have chosen addition.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d + %d = %d", num1, num2, num1+num2);
}
else if(tolower(x) == 's')
{
P("\nYou have chosen subtraction.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d - %d = %d", num1, num2, num1-num2);
}
else if(tolower(x) == 'm')
{
P("\nYou have chosen multiplication.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%d * %d = %d", num1, num2, num1*num2);
}
else if(tolower(x) == 'd')
{
P("\nYou have chosen division.");
num1 = askForNumber("\n\nEnter 1st number: ");
num2 = askForNumber("\nEnter 2nd number: ");
P("\n\n%g* %g = %.2f", (float)num1, (float)num2, (float)(num1/num2));
}
else
{
P("\nYou have entered an invalid character!");
P("\n\nAnswer: ");
continue;
}
while(loop[2] == 1)
{
P("\n\nDo you want to do another calculation? Y/N: ");
y = getchar();
if(tolower(y) == 'y' || tolower(y) == 'n')
{
loop[2] = 0;
}
else
{
P("\nYou have entered an invalid character.");
continue;
}
}
loop[1] = 0;
}
if(tolower(y) == 'y')
{
continue;
}
if(tolower(y) == 'n')
{
loop[0] = 0;
}
}
}
int askForNumber(const char *string)
{
P("%s", string);
while(loop[3] == 1)
{
fgets(input, (sizeof(input)/sizeof(input[0]))-1, stdin);
if(sscanf(input, "%d", &num) != 1)
{
num = 0;
P("Invalid number!");
continue;
}
return num;
}
}
I have these bugs:
After I finish a calculation, and press 'Y', it clears the screen non-stop.
After "Enter 1st number: ", the "Invalid number" shows up once even though I haven't typed anything yet(but i can still input a number and it will be saved to 'num1', "Invalid number just bugs me".
At the top where I am to input 'a' or 's' or 'm' or 'd' to choose an operation, if I put some letter except for that above, i get this
OUTPUT:
Answer: o
You have entered an invalid character!
Answer:
You have entered an invalid character!
Answer:
the error shows up twice, but i only typed once.
When there are no characters in the input buffer, the getchar function blocks until the return key is pressed. All keys, including return, are stored in the input buffer, then getchar returns the first character in the buffer. The next call to getchar will immediately return the next character in the buffer.
So if you press 'y' then return, the first call to getchar returns the 'y' character, and the next returns a newline character, i.e. the return key.
You need to flush the input buffer each time you use getchar to skip over the newline:
do {
c = getchar();
} while (c == '\n');
You nedd #include ctype.h to lower is part of that library tolower uses this library and its nowhere in your code