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;
}
Related
I am new to programming and learning the C language and was practising structures and was trying to make basic school management system by using structures, but I am getting
too many errors (by using pointers in structures). So, can you please tell me what are the errors and how can I avoid these types of mistakes. Because, according to my understanding this should have been working.
Here is my code:
#include <stdio.h>
struct student {
int rollno;
char name[20];
float marks;
};
int main() {
again:;
while (1 == 1) {
struct student array[60];
char input;
int roll;
printf("What you would like to do:\n");
printf("Enter 'R' to fill the details again of all the student\n Enter 'U' to edit the
details of a single student\n");
printf("Enter 'S' to see the details of a particular student\n Enter 'A' to see the
details of every student\n");
scanf("%c", &input);
if (input == 'A' || 'a') {
for (int i = 0; i < 60; i++) {
printf("Roll no. : %d\n Name : %s\n Marks : %f\n", array[i].rollno, array[i].name,
array[i].marks);
}
}
else if (input == 'R' || 'r') {
for (int i = 0; i < 60; i++) {
printf("Roll no. os student is : %d\n", (i + 1));
printf("Enter students name :\n");
gets(array[i].name);
printf("Enter students marks :\n");
scanf("%f", &array[i].marks);
}
}
else if (input == 'S' || 's') {
printf("Enter the roll no. of the student of whom you want to see the details :\n");
scanf("%d", &roll);
printf("Roll no. :\n %d\n", roll);
printf("Name : \n");
puts(array[(roll - 1)].name);
printf("Marks : \n %f \n", (*(array + (roll - 1))->marks));
}
else if (input == 'U' || 'u') {
printf("Enter the roll no. of the student of whom you want to see the details :\n");
scanf("%d", &roll);
printf("Enter the name :\n");
gets((*(array + (roll - 1))->name));
printf("Enter the marks :\n");
scanf("%f", &(*(array + (roll + 1))->marks));
} else {
printf("Error Occured!!! \n");
printf("Re-enter your input\n");
goto again;
}
}
return 0;
}
There are many problems in your code:
there is no need for a goto again;, you already have an infinite loop while (1 == 1), which is usually written for (;;) in C. Don't use goto.
the definition struct student array[60]; should be moved outside the scope of the loop body. As posted, the array is discarded after each iteration and its contents become indeterminate.
array should be initialized to avoid undefined behavior when printing the contents before reading it from the user.
string literals cannot span multiple lines in a C source file. You can split them this way for readability:
printf("What you would like to do:\n"
"Enter 'R' to fill the details again of all the student\n"
"Enter 'U' to edit the details of a single student\n"
"Enter 'S' to see the details of a particular student\n"
"Enter 'A' to see the details of every student\n");
you should have a menu option to quit the program
reading a single character with scanf("%c", &input) is tricky: scanf() will read the pending newline from a previous call. You should use scanf(" %c", &input) where the space will cause pending whitespace to be read and discarded.
if (input == 'A' || 'a') does not test for A or a, it compares input to 'A' and if different compares 'a' to zero, hence the test is always true. You should write:
if (input == 'A' || input == 'a')
gets(array[i].name); is a NO NO. Don't use gets(), throw away the book that tells you to use it. For consistency with the other inputs, you can use
scanf("%19[^\n]", array[i].name);
Note that 19 tells scanf() the maximum number of characters to store into array[i].name before the null terminator, preventing undefined behavior for longer user input, and [^\n] causes scanf() to read and store characters up to and not including the newline character. %19s would stop at any white space, preventing the input of multiple words such as James Bond.
scanf("%f", &(*(array + (roll + 1))->marks)); is a very contorted way to write:
scanf("%f", &array[roll + 1].marks);
you should check the return value of scanf() to detect invalid input and flush the pending input on error.
Here is a modified version:
#include <stdio.h>
struct student {
int rollno;
char name[20];
float marks;
};
int main() {
struct student array[60] = { 0 };
int len = sizeof(array) / sizeof(*array);
int c, i, roll;
char input;
for (;;) {
printf("What you would like to do:\n"
"Enter 'R' to fill the details of all the student\n"
"Enter 'U' to edit the details of a single student\n"
"Enter 'S' to see the details of a particular student\n"
"Enter 'A' to see the details of every student\n"
"Enter 'Q' to quit the program\n");
if (scanf(" %c", &input) != 1)
break;
if (input == 'A' || input == 'a') {
for (i = 0; i < len; i++) {
printf("Roll no.: %d\nName: %s\nMarks: %f\n",
array[i].rollno, array[i].name, array[i].marks);
}
} else
if (input == 'R' || input == 'r') {
for (i = 0; i < len; i++) {
printf("Roll no. os student is: %d\n", i + 1);
printf("Enter student's name:\n");
if (scanf("%19[^\n]", array[i].name) != 1)
break;
printf("Enter students marks:\n");
if (scanf("%f", &array[i].marks) != 1)
break;
}
if (i < len) {
printf("Invalid input\n");
}
} else
if (input == 'S' || input == 's') {
printf("Enter the roll no. of the student of whom you want to see the details:\n");
if (scanf("%d", &roll) == 1 && roll >= 1 && roll <= len) {
printf("Roll no.: %d\nName: %s\nMarks: %f\n",
roll, array[roll - 1].name, array[roll - 1].marks);
} else {
printf("Invalid Roll no\n");
}
} else
if (input == 'U' || input == 'u') {
printf("Enter the roll no. of the student of whom you want to see the details:\n");
if (scanf("%d", &roll) == 1 && roll >= 1 && roll <= len) {
printf("Enter the name:\n");
scanf("%19[^\n]", array[roll - 1].name);
printf("Enter the marks:\n");
scanf("%f", &array[roll - 1].marks);
} else {
printf("Invalid Roll no\n");
}
} else
if (input == 'Q' || input == 'q') {
return 0;
} else {
printf("Invalid entry\n");
printf("Re-enter your input\n");
}
/* read and discard the rest of the input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
}
printf("Premature end of file\n");
return 0;
}
Im making a calculator with A LOT of functions, Im not nearly done with the functions. But I thought, I want the program active after returning me the value I asked for. My logic was to put it into a while loop, but clearly my idea and how I put it are not equal. Or maybe my logic doesnt work in this case. Anyway, imagine I ask the program how much its 2+2 and it returns me 4. Done, but I want it to ask me again for another operation, how can I do that?
Im really new with this stuff, so thanks for the help.
To resume the code below. I ask for a value, then scan it, then ask for a operator, then I ask wether if the user want to continue or not, if he says yes thats the condition for the loop ---> while(condition != 'yes' );{
And if not, just end the program. And I putted the operations inside the loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int input;
double sinus;
int op;
printf(" What function do you want to use? \n \n --------------------------------------- \n");
printf(" BASIC OPERATIONS --> type 1 \n --------------------------------------- \n");
printf(" TRIGONOMETRIC FUNCTIONS \n sin --> type 2 \n cos --> type 3 \n tan --> type 4 \n arcsin --> type 5 \n arccos --> type 6 \n arctan --> type 7 \n --------------------------------------- \n");
scanf("%d", &op);
char condition[5];
printf("Stop? Type: yes or no");
scanf("%s", &condition);
while(condition != 'yes' );{
if (op == 1) {
double val1;
char op1;
double val2;
printf("Please type a number: \n" );
scanf("%lf", &val1);
printf("Please type an operator: \n" );
scanf(" %c", &op1);
printf("Please type another number: \n" );
scanf("%lf", &val2);
if (op1 == '+') {
printf("%f \n", val1 + val2);
}
if (op1 == '-') {
printf("%f \n", val1 - val2);
}
if (op1 == '*') {
printf("%f \n", val1 * val2);
}
if (op1 == '/') {
printf("%f \n", val1 / val2);
}
}
else if (op == 2) {
double arg;
printf("Please type the argument of sin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", sin(arg));
}
else if (op == 3) {
double arg;
printf("Please type the argument of cos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", cos(arg));
}
else if (op == 4) {
double arg;
printf("Please type the argument of tan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", tan(arg));
}
else if (op == 5) {
double arg;
printf("Please type the argument of arcsin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", asin(arg));
}
else if (op == 6) {
double arg;
printf("Please type the argument of arccos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", acos(arg));
}
else if (op == 7) {
double arg;
printf("Please type the argument of arctan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", atan(arg));
}
else {
printf("%d", 0);
}
}
}
Sorry for too many to read:((( Im not experienced with forums.
The following example will give you an idea how things can be repeated based on input.
check how strcmp is done,that way you are doing is wrong.
Also consider using switch for handling multiple cases of input and their operations.
#include<stdio.h>
#include <string.h>
#include <ctype.h> // isspace
int main() {
char choice[] = "Yes";
do{
int i = 0;
/**
* implement all you want here
*/
printf("Enter Yes to repeat, to exit enter any other non blank string\n");
while(isspace(choice[i] = getchar()));
while((choice[++i] = getchar()) != '\n');
choice[i] = '\0';
printf("choice = %s, i = %d\n", choice, i);
}while(!strcmp(choice,"Yes") );
return 0;
}
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;
}
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 ==.
#include<stdio.h>
int main(void)
{
int sum(), sub(), mul(), div();
char ans;
printf("\ta) Add\n");
printf("\tb) Sub\n");
printf("\tc) Multiply\n");
printf("\td) Divition\n");
scanf_s("%c",&ans);
printf("\nYour answer is %c",ans);
if((ans == 'A')||(ans == 'a'))
printf("The sum of Two number is %d\n",sum());
else if((ans == 'B')||(ans == 'b'))
printf("The subraction of Two number is %d\n",sub());
else if((ans == 'C')||(ans == 'c'))
printf("The product of two number is %d\n",mul());
else if((ans == 'D')||(ans == 'd'))
printf("The divition of two number is %d\n",div());
else
printf("Enter the valid option\n");
}
int sum()
{
int x,y;
printf(" Addition\n");
printf("Enter the first number = ");
scanf_s("%d",&x);
printf("Enter the second number = ");
scanf_s("%d",&y);
return x+y;
}
int sub()
{
int x,y;
printf(" Subraction\n");
printf("Enter the first number = ");
scanf_s("%d",&x);
printf("Enter the second number = ");
scanf_s("%d",&y);
return x-y;
}
int mul()
{
int x,y;
printf(" Mltification\n");
printf("Enter the first number = ");
scanf_s("%d",&x);
printf("Enter the second number = ");
scanf_s("%d",&y);
return x*y;
}
int div()
{
int x,y;
printf(" Divition\n");
printf("Enter the first number = ");
scanf_s("%d",&x);
printf("ENter the second number = ");
scanf_s("%d",&y);
return x/y;
}
scanf_s("%c",&ans);
the function scanf does not recognize my input
whats wrong in the code
when i use
ans=getchar();
is working perfect but.. the scanf does not recognize what i input
can any one explain the problem in the code iam using visual studio 2010
To scan a single char you have to put a blank space before %c:
scanf(" %c", &char);
The blank space is needed to consume any \n char in the input buffer. You must put the blank space just for char type.