Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I tried using the ASCII code too by replacing %d with %c in `scanf() code. but then it displays - Add=5 (If I put the input 5 & 6 with 65 ASCII code)
#include <stdio.h>
#include <conio.h>
void main()
{
int num1,num2,res;
char ch;
printf("Enter two numbers");
scanf("%d%d",&num1,&num2);
printf("Enter the operator from the following\n\nA for +\nB for -\nC for*\nD for /\n");
scanf("%c",&ch);
if(ch=='A')
{
res=num1+num2;
printf("Add=%d",res);
}
else if(ch=='B')
{
res=num1-num2;
printf("Sub=%d",res);
}
else if(ch=='C')
{
res=num1*num2;
printf("Mul=%d",res);
}
else if(ch=='D')
{
res=num1/num2;
printf("Div=%d",res);
}
else
{
printf("Invalid Operator");
}
getch();
}
The output:
Any help?
You are facing, sadly, the same problem faced by every beginning C programmer ever: scanf sucks. When you called
scanf("%d%d",&num1,&num2);
it correctly read the two numbers that you typed. But after you typed the two numbers, you probably hit RETURN. And the first call to scanf did not read that return character. So it's still sitting there in the input buffer, and when you later call scanf("%c",&ch), it's actually the newline character that gets read, not the A or B that you wanted to read.
Without changing your program at all, you can try typing something like
12 34A
in response to the first prompt. The first scanf won't read it, so now it will be sitting there in the input buffer waiting for your second call to scanf to find it.
That's a workaround, not a fix. To fix it, you could do what #Ediac suggested in his answer.
(A better fix would probably be not to use scanf at all, but unfortunately that involves learning more about I/O than your book or instructor probably wanted to get into right at first.)
I'd rather write a more useful and correct version of this code
#include <stdio.h>
int main() {
int n1, n2, ans;
char op;
scanf("%d %c %d", &n1, &op, &n2);
switch (op) {
case '+':
ans = n1 + n2;
break;
case '-':
ans = n1 - n2;
break;
case '*':
ans = n1 * n2;
break;
case '/':
if (n2) {
ans = n1 / n2;
break;
}
default:
fprintf(stderr, "Invalid Input\n");
return 1;
}
printf("%d", ans);
return 0;
}
Input
1 + 2
4-3
Output
3
1
See http://ideone.com/y2nnWF demo.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For example, if I want to call switch statement in for loop, I got an error.How can I correct this issue?If I want to move my switch statement outer part in determined condition which is to be using more than calling switch statement. Thanks in advance.
#include<stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#define SIZE 50
int i = 0;
int main() {
char usertxt[SIZE], myoperator[SIZE];
printf("addition='+',subtraction='-',multiplication='*',division='/'\n");
usertxt[0] = 0;
int x, myarray[SIZE];
printf("How many numbers should be entered? ");
scanf_s("%d", &x);
for (i = 0; i < x; i++) {
scanf_s(" %c", &myoperator[i], 1);
switch (myoperator[i]) {
case '+':printf("Addition operation\n");
printf(" Enter your number: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '-':printf("Subtraction operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '*':printf("Multiplication operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
case '/':printf("Division operation\n");
printf("Enter your numbers: ");
scanf_s("%d", &myarray[i]);
usertxt[i] = printf("%d%c", myarray[i], myoperator[i]);
break;
default :if (myoperator[i] == '\0') {
break;
};
}
}
}
As #Gerhardh said, welcome to SO.
But I really think that the logic behind your code isn't good enough.
I take some time to understand your goal and I make a new clearer version.
While testing and understanding your code, I've encountered the following problems:
Implicit declaration of function 'scanf_s' is invalid in C99
Declarations of global variables as counters and their usage inside the loop were the main reason why your code doesn't work as expected.
The printf() function is used for printing the output. It returns the number of characters that are printed. If there is some error then it returns a negative value. You used it like it returns a char or even a string.
Switch statement is useless if you have to do always the same operations.
Char reading doesn't work correctly.
I'm gonna attach here the updated code. Hope that it could be helpful and that actually it has the same "goal" that your code has.
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#define SIZE 500
#define nOperator 4
int main() {
char usertxt[SIZE], myoperator[nOperator];
printf("addition='+',subtraction='-',multiplication='*',division='/'\n");
usertxt[0] = 0;
int nOperations;
int x, myarray[SIZE];
printf("How many numbers should be entered? ");
scanf("%d", &x);
printf("How many operations would you like to try? ");
scanf("%d", &nOperations);
for (int i = 0; i < nOperations; i++) {
fseek(stdin, 0, SEEK_END);
printf("\n\nEnter operation #%d: ", i + 1);
myoperator[i] = getchar();
for (int j = 0; j < x; j++) {
printf("Enter number #%d: ", j + 1);
scanf("%d", &myarray[j]);
}
int k = 0;
for (int m = 0; m < x; m++) {
if (m == x - 1) {
usertxt[k] = myarray[m];
printf("%d", myarray[m]);
} else {
usertxt[k] = myarray[m];
usertxt[k + 1] = myoperator[i];
printf("%d%c", myarray[m], myoperator[i]);
}
k++;
}
printf("\n\n");
}
}
As you can see, I tried to stay as much as next to your code idea and implementation.
For instance, I've not deleted the initial pragma and define. Probably you are going to use them later.
I've used fseek(...) as suggested here:
How to clear input buffer in C?
in order to read correctly char and integers together.
First thing first, it reads the numbers that you want to use and the number of operations that you want to do. After that, it takes the numbers associated with a certain operation, and at the end, it prints the expression as you are doing in your own code.
If you want to add the result, you just need a little edit in the code to sum all the numbers in the array or counting them while reading from input.
Variable Counters Description:
i is for 'myoperator' array
k is for 'usertxt' array
m is for 'myarray' array
Next steps:
Add the result variable to display the result of the operation
Use dynamic memory
Note that:
fseek(...) works on some systems; if not, then it is not surprising as nothing guarantees that it will work when standard input is an interactive device (or a non-seekable device like a pipe or a socket or a FIFO, to name but a few other ways in which it can fail).
If you need that it has to be portable, then check the link that I've placed before.
Hope that it was helpful.
Cheers,
Denny
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to develop a quiz type math game in which the user has to solve on 1-5 questions. I want to add a counter that will display all the correct and incorrect answers at the end of the quiz, so far I have been doing it using if else statement, but I feel like there's should be a more efficient way of doing it. My code:
if ( questions == 2 )
{
printf (" What is 2 + 2\n");
scanf("%d",&A1);
if( A1 == 4 )
{
correct ++;
}
else
{
incorrect ++;
}
printf (" What is 5 + 2\n");
scanf("%d",&A2);
if( A2 == 7 )
{
correct ++;
}
else
{
incorrect ++;
}
}
Here's the code i have the same thing written 5 times for each option that the user can pick. All help is greatly appreciated, thanks in advance!
You could use the total of the questions and substract the correct answers to get the number of incorrect answers. Here is a sample:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char arQuestions[5][20] = { "2 + 2 =",
"2 * 2 =",
"2 - 2 =",
"2 / 2 =",
"2 ^ 2 ="};
int answers[5] = {4,4,0,1,4};
int i = 0;
int answer = 0;
int correct = 0;
for(;i<5;++i)
{
printf("%s ", arQuestions[i]);
if( 1 == scanf("%d", &answer))
if(answer == answers[i])
correct++;
printf("correct<%d> incorrect<%d>\n", correct, (i+1)-correct);
}
return(0);
}
Switch statements can be used when you need to check one variable against multiple values (as you do with your if ( questions == 0...5 ). In order not to rewrite the same questions over and over, we can use the way the switch statement naturally overruns into the next case to "cascade" depending on the number of questions we want.
Finally, as some other pointed out, we don't need to separate variables to track correct or incorrect answers; just track correct answers, and at the end the incorrect answers would equal questions - correct.
Putting that all together, we have something that looks like this:
int questions;
printf("Number of questions?\n");
scanf("%d",&questions);
int correct = 0;
int answer = 0;
switch(questions) {
case 5:
printf("What is 2 + 2?\n");
scanf("%d",&answer);
if(answer == 4)
{
correct++;
}
//note - no break at end of each case
case 4:
//ask another question
case 3:
//ask another question
case 2:
//ask another question
case 1:
//ask another question
default:
break;
}
printf("Results:\nCorrect = %d\nIncorrect = %d", correct, questions - correct);
There is another option that might be a little more efficient
you can make correct and incorrect global variables or create a pointer to them, and create another function to check if the entered answer is correct and update correct or incorrect accordingly:
// initiate global variable's
int correct = 0, incorrect = 0;
void checkanswer(int var1, int var2, int useranswer)
{
if(useranswer == var1 + var2)
correct++;
else
incorrect++;
}
int main(void)
{
...
printf (" What is 2 + 2\n");
scanf("%d", &A1);
checkanswer(2, 2, A1);
//next question
}
This way, instead of repeating yourself, you use the function you wrote.
A few other things:
Try to find an alternative to scanf, it is a dangerous function that make your code vurnable. See this and or search for more answers cause this topic has a lot of answered questions online.
I wrote a math game as well, if you want some another example for something similar to what your'e writing. In my game you need to get a score of 10 and the questions are random in any game. See here if your'e interested.
Hope I helped!
Feel free to ask me about my game if you have any questions or anything else :)
Here's a more generic version which actually calculates the equation and checks it against the user's answer.
#include <stdio.h>
typedef enum
{
ADD,
SUB,
MUL,
DIV,
} operation_t;
typedef struct
{
int op1;
int op2;
operation_t op;
} equation_t;
char operation_to_char (operation_t op)
{
const char CH_OP[] = {'+', '-', '*', '/'};
return CH_OP[op];
}
int solve (const equation_t* eq)
{
switch(eq->op)
{
case ADD: return eq->op1 + eq->op2;
case SUB: return eq->op1 - eq->op2;
case MUL: return eq->op1 * eq->op2;
case DIV: return eq->op1 / eq->op2;
}
return 0; // to silence compiler warning, should never happen
}
int main (void)
{
const equation_t EQUATIONS[] =
{
{1, 1, ADD},
{2, 2, ADD},
{1, 1, SUB},
{2, 2, MUL},
{9, 3, DIV},
};
const size_t EQUATIONS_N = sizeof(EQUATIONS)/sizeof(*EQUATIONS);
for(size_t i=0; i<EQUATIONS_N; i++)
{
printf("What is %d %c %d? ",
EQUATIONS[i].op1,
operation_to_char(EQUATIONS[i].op),
EQUATIONS[i].op2);
int answer;
scanf("%d", &answer);
getchar(); // discard line feed
int solution = solve(&EQUATIONS[i]);
if(answer == solution)
{
puts("Correct");
}
else
{
printf("Incorrect, the solution is %d\n", solution);
}
}
}
Please note that this code has no error handling of user input.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
A have a problem with my program. I dont know what im doing wrong but loop do while doesnt work. At and program should ask "If you want to run this program again, press T.Other key should close this program.
#include "stdafx.h"
#include <stdlib.h>
#include <conio.h>
#include <time.h>
int main()
{
int a;
int b;
int c;
int f;
int g;
int h;
int d = 0;
char e;
srand(time(0));
do {
printf("How many numbers do you want to show: ");
scanf_s("%i", &a);
printf("od: ");
scanf_s("%i", &b);
printf("do: ");
scanf_s("%i", &c);
h = c + 1;
f = b - h;
for (d; d < a; d++) {
printf("%i ", b + rand() % f);
}
printf("\n");
printf("Restart program? T- Yes");
scanf_s("%s", &e);
} while (e == 't');
_getch();
return 0;
}
Program works fine, but when i press T at the end. it will close. Im using Visual Studio 2015
Now my code is below:
do {
printf("How many numbers do u want: ");
scanf_s("%i", &a);
printf("od: ");
scanf_s("%i", &b);
printf("do: ");
scanf_s("%i", &c);
h = c + 1;
f = b - h;
//printf("%i %i %i\n", h, f);
for (d; d < a; d++) {
printf("%i ", b + rand() % f);
}
printf("\n");
printf("Restart? T- yes");
scanf_s("%c", &e);
} while (e == 't' || e == 'T');
_getch();
return 0;
}
But it still doesnt work. I cant enter any letter. When i press any key a windows is going to close
As others have pointed, this is because you're trying to get a "%s" and, therefore, you can't compare it to a character. Use "%c" instead, or use strcmp function to compare 2 char arrays.
By the way, be aware that scanf_s is a Microsoft only function. Not sure if visual studio is forcing you to use it, but the common usage of scanf wouldn't hurt, check it out:
scanf("%c", &e);
Do you press 'T'? because 'T' and 't' are not the same character. check the ascii table
Your program will continue while you press a 't' so with a 'T' or anything else it will stop.
ps: You may want to use "read(0, &e, 1);" or "scanf_s("%c", &e);" instead of "scanf_s("%s", &e);" (last line of do while), because you have a char and if you enter a string like "Mr T. says yes" it will overwrite your memory which is never good.As a reminder char is 1 byte in memory, with '&' you can access its place in memory, so it acts like a string but if you write more than 1 character it will just write in the following memory which isn't attributted to your program. it will probably do nothing but it can overwrite another of your variable or worse overwrite another program in your computer (hopefully not something important like a window's program or else!)
char and string basics
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I made a program which takes a user to input number, if user inputed number less than 0 or greater than 100, then program returns to main function.
Here is my code:
#include <stdio.h>
int main(){
int a; scanf("%d", &a);
if(a > 100 || a < 0) {
printf("Going back to program.");
return main();
} else {
printf("Your number: %d\n", a);
}
}
But this code doesn't take a input and it just prints "Your number: 0".
So, what is wrong with this code?
Using recursion here (calling main again from main) is overly complicated and useless.
You want this:
#include <stdio.h>
int main()
{
int a;
do
{
scanf("%d", &a);
} while (a > 100 || a < 0); // simply repeat scan if a is out of bounds
printf("Your number: %d\n", a);
}
This is basic C knowledge. You probbaly should start reading your C textbook.
Your code is not good... A better way of doing it would be to use a loop
Better Solution
int main(){
int a;
do {
scanf("%d", &a);
} while(a > 100 || a < 0);
printf("Your number: %d\n", a);
return 0;
}
Your working solution
int main(){
int a;
scanf("%d", &a);
if(a > 100 || a < 0) {
printf("Recursion");//You are not going back you go further in depth (Recursion)
return main();
} else {
printf("Your number: %d\n", a);
return 0;//You need to return in if and in else
}
}
This is basic knowledge about programming (with c). I think you are a beginner so maybe you want to start with an Tutorial?
There is nothing wrong with your code, it should work.
scanf() reads from stdin. Depending on how and where your program runs stdin can have different meanings.
On tutorialspoint.com, you have to supply data to stdin before running your program by using the "Stdin" tab.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to write a small function that will get a number.
The function should be idiot-proof so it would give warnings if ie. someone entered a character instead.
I wrote a function like the one below, but if I enter a non-int the program gives me an infinite loop, constantly repeating the printf "Not a valid number" so I never get a chance to do the correct input.
The code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
for (int ret = 0; ret < 1;)
{
int num;
printf("\n Please input a number: ");
ret = scanf ("%d", &num);
if (ret < 1)
printf ("\nNot a valid number!");
else
printf("\nYou input %d", num);
}
return 0;
}
How to fix it?
Replace this line if (y = 0) with this if (y == 0).
Note the line below with the comment about eating the input buffer. Since your scanf didn't find what it is looking for in the input buffer, the wrong input just stays there and fails forever unless you do something to "eat" it.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("Hello world!\n");
while ('A')
{
int x, y;
printf("\n x: ");
y = scanf ("%d", &x);
printf("\nx = %d", x);
if (y < 1)
{ // eat the input buffer so we can try again
while ( getchar() != '\n' );
printf ("\nWRONG!");
}
}
return 0;
}