I need to ask an input from a user and he/she should have the ability to write a float number, and I need to do some calculation on the 2 numbers, but I'm having a problem after the isdigit test...even if I enter an integer its going to the continue;
This is my code:
#include <stdio.h>
#include <ctype.h>
char get_choice(void);
float calc(float number1, float number2);
int main()
{
float userNum1;
float userNum2;
get_choice();
printf("Please enter a number:\n");
while ((scanf("%f", &userNum1)) == 1)
{
if (!isdigit(userNum1))
{
printf("Please enter a number:\n");
continue;
}
printf("Please enter another number:\n");
while ((scanf("%f", &userNum2) == 1))
{
if (!isdigit(userNum2))
{
printf("Please enter a number:/n");
continue;
}
else if (userNum2 == '0')
{
printf("Please enter a numer higher than 0:\n");
continue;
}
}
}
calc(userNum1, userNum2);
return 0;
}
float calc(float number1, float number2)
{
int answer;
switch (get_choice())
{
case 'a':
answer = number1 + number2;
break;
case 's':
answer = number1 - number2;
break;
case 'm':
answer = number1 * number2;
break;
case 'd':
answer = number1 / number2;
break;
}
return answer;
}
char get_choice(void)
{
int choice;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply d. divide\n");
printf("q. quit\n");
while ((choice = getchar()) == 1 && choice != 'q')
{
if (choice != 'a' || choice != 's' || choice != 'm' || choice != 'd')
{
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply d. divide\n");
printf("q. quit\n");
continue;
}
}
return choice;
}
Apologize for uploading the functions as well, but since I'm a newbie the problem might be there.
Cheers.
isDigit() only takes a character input.
The best way to check that you are getting input correctly is to use
if(scanf("%f", &userNum) != 1) {
// Handle item not float here
}
Since scanf() will return the number of items correctly scanned.
IsDigit() Function check only if the character is decimal digit or not.
Let say:
int isdigit ( int c );
Checks whether c is a decimal digit character.
Decimal digits can be any of: 0 1 2 3 4 5 6 7 8 9.
The isdigit() function will return non-zero if c is a decimal digit; otherwise, it shall return 0.
You can also try something like this:
int get_float(char *val, float *F){
char *eptr;
float f;
errno = 0;
f = strtof(val, &eptr);
if(eptr != val && errno != ERANGE){
*F = f;
return 1;
}
return 0;
If val points to float number function return 1 & put this number to *F, else it returns 0.
Related
I am trying to create a program that assigns the user one of three questions at random. I figured out that part however I want to make it so that after they correctly answer their assigned question that they are asked if they want to take another one.
int main(void) {
srand(time(0));
int luckyNumber;
int quizNumber;
int score;
int totalScore;
int averageScore;
int attempts;
char answer1;
char answer2;
char answer3;
char opt1;
char loop = 'y';
printf("Welcome to the quiz program!\n");
while(loop == 'y') {
printf("Please enter a lucky number between 1 and 9: ");
scanf("%d", &luckyNumber);
quizNumber = rand() % 3 + 1;
printf("Your quiz number is %d\n", quizNumber);
if (quizNumber == quizNumber) {
while (score != 5) {
printf("Quiz 1\n");
printf("A. True\n");
printf("B. False\n");
printf("Enter your answer: ");
scanf(" %c", &answer1);
if (answer1 == 'B' || answer1 == 'b') {
printf("Correct!\n");
score = score + 5;
break;
}
else {
printf("Incorrect!, Try again.\n");
printf("\n");
}
break;
}
break;
}
printf("Would you like to go again y/n?");
scanf("%c", &loop);
if (loop != 'y')
loop = 'n';
}
return 0;
}
The problem I am having is after I compile the code, it stops when the correct answer is input rather than going on to ask if the user would like to do another quiz.
Hello so I've been working a little prgramme which is sort of a calculator (I'm a beginner) and well as you can see in the tittle at then end of the code, the two if strcmp doesn't work. And vscode is telling me (for the strcmp) Exception has occurred. Segmentation fault. But gcc is telling me what is in the tittle.
#include <stdio.h>
#include <string.h>
int main()
{
float num1;
float num2;
float anwser;
int rnum = 1;
int hi = 0;
char operator;
char ifyorn;
char y = 'y';
char n = 'n';
while (hi == 0)
{
printf("Enter operator +, -, /, x: ");
scanf(" %c", &operator);
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
switch (operator)
{
case '+':
anwser = num1 + num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '-':
anwser = num1 - num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case 'x':
anwser = num1 * num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '/':
anwser = num1 / num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
default:
printf("This is not a valid character please try again :(");
break;
}
if(strcmp (ifyorn, n) == 0)
{
printf("%f", anwser);
hi == 1;
}
if(strcmp (ifyorn, y) == 0)
{
hi == 0;
}
}
}
The variables ifyorn, y and n are declared having the type char.
char ifyorn;
char y = 'y';
char n = 'n';
The function strcmp expects arguments of the pointer type char * that point to strings.
So these if statements
if(strcmp (ifyorn, n) == 0)
and
if(strcmp (ifyorn, y) == 0)
are incorrect. Instead you should write
if ( ifyorn == n )
and
if ( ifyorn == y )
Also instead of assignments you are using the comparison operator in these statements
hi == 1;
and
hi == 0;
You need to write
hi = 1;
and
hi = 0;
Increasing the variable rnum looks senseless
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
Why not just to write
printf("Enter num %d :", 1 );
scanf("%f", &num1);
printf("Enter num %d :", 2 );
scanf("%f", &num2);
And in the code snippet under the label default you should add one more statement
default:
printf("This is not a valid character please try again :(");
ifyorn = y;
break;
You don't have to be mean to the guy ,he is learning.
You are getting this error because you are passing characters to strcmp() instead of pointers to characters.
Here is more information regarding that function.
https://www.programiz.com/c-programming/library-function/string.h/strcmp
#include <stdio.h>
#include <conio.h>
void Calculator();
void main()
{
Calculator();
getch();
}
void Calculator()
{
int n,j;
char f1;
double t;
printf("please enter two numbers");
scanf("%d%d",&n,&j);
printf("please enter the syboml you want ( * / + or -)");
scanf("%c",&f1);
if( f1 == '+')
t = n + j;
if (f1 == '-')
t = n-j;
if (f1 == '*')
t = n*j;
if (f1 == '/')
t = n/j;
printf("%f" ,t);
}
In your final printf, you are using t that has never been initialized, and might hold a garbage value if no-one of those if conditions is met.
Consider initializing t (a simple = 0 does the job) or add an else clause somewhere
Edit:
While I was at it, I also made some changes to make sure the second scanf ignores the trailing /n without using fflush.
Edit 2:
As suggested by HAL9000, assuming that an initialization to 0 would be enough is wrong. I modified the second part of the program to make use of a switch-case and eventually reject an invalid operator.
The final code looks like this
#include <conio.h>
#include <stdio.h>
void Calculator();
int main() {
Calculator();
getch();
return 0;
}
void Calculator() {
int n, j;
char f1;
double t;
printf("please enter two numbers: ");
scanf("%d%d", &n, &j);
printf("please enter the symbol you want ( * / + or -): ");
scanf(" %c", &f1);
switch (f1) {
case '+':
t = n + j;
break;
case '-':
t = n - j;
break;
case '*':
t = n * j;
break;
case '/':
t = (float)n / j;
break;
default:
printf("Invalid symbol, please use ( * / + or -)\n");
return;
}
printf("%f\n", t);
}
In some compilers, you might be getting this t is not initialized error as your code will never ask please enter the symbol you want ( * / + or -) because scanf("%c",&f1); will take input as trailing newline char, so t never gets initialized. I ran your code in GCC compiler on mac but got output as 0.0000 as t will never be initialized in your case.
You can just eat up the trailing char for that you can use getchar(); or you can also put a space in the format string, e.g. scanf(" %c",&f1); to consume the newline character.
void Calculator()
{
int n,j;
char f1;
double t;
printf("please enter two numbers");
scanf("%d%d",&n,&j);
printf("please enter the syboml you want ( * / + or -)");
scanf(" %c",&f1);
if( f1 == '+')
t = n + j;
if (f1 == '-')
t = n-j;
if (f1 == '*')
t = n*j;
if (f1 == '/')
t = n/j;
printf("%f" ,t);
}
Not every program path leads to the assignment of the t variable. So it can be used in the printf not initialized.
switch(f1)
{
case '+':
t = n + j;
break;
case '-':
break;
t = n-j;
case '*':
t = n*j;
break;
case '/':
t = n/j;
break;
default:
t = 0;
break;
}
Now t will always will be assigned with the value.
Some additional remarks:
Always check the return value of the scanf
Your main definition is invalid. If main does not take any parameters is has to be int main(void)
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
I want to use a get choice function to let user choose a letter from a menue, and i want to use this value to switch it in a float function...i know its only possible to use switch as type int, but will the value i will get is going to be float?
float calc(float number1, float number2)
{
int answer = get_choice();
switch (answer)
{
case 'a':
answer = number1 + number2;
break;
case 's':
answer = number1 - number2;
break;
case 'm':
answer = number1 * number2;
break;
case 'd':
answer = number1 / number2;
break;
}
return answer; }
char get_choice(void)
{
int choice;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply d. divide\n");
printf("q. quit\n");
while ((choice = getchar()) == 1 && choice != 'q')
{
if (choice != 'a' || choice != 's' || choice != 'm' || choice != 'd')
{
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply d. divide\n");
printf("q. quit\n");
continue;
}
}
return choice; }
float calc(float number1, float number2)
{ int choice = get_choice();
float answer = 0.0;
switch (choice)
There is no need to reuse the variable. You can also switch a char variable directly.
Any non-zero value is true so you should code
while ((choice = getchar()) != EOF && choice != 'q')