I'm a newbie learning code so this might be pretty simple but I can't understand what is happening.
When I try to run the following code it seems to hang on the while loop condition and doesn't execute any code after that. Is the != operator not suited for this?
I also tried a do {} while and everything ran fine but as soon as I set the operator to 'E', again the condition seems to hang there and doesn't get out of the loop.
#include <stdio.h>
int main(void) {
float n, content;
char operator;
n = content = 0;
operator = 'a';
printf("Begin Calculations:\n");
while (operator != 'E');
{
scanf("%f %c", &n, &operator);
switch (operator) {
case 's':
case 'S':
content = n;
printf("= %f\n", content);
break;
case '+':
content = content + n;
printf("= %f\n", content);
break;
case '-':
content = content - n;
printf("= %f\n", content);
break;
case '*':
content = content * n;
printf("= %f\n", content);
break;
case '/':
content = content / n;
printf("= %f\n", content);
break;
case 'e':
case 'E':
printf("End of calculations\n");
operator == 'E';
break;
default:
printf("Invalid input\n");
break;
}
}
return 0;
}
Remove the semicolon at the end of the while statement:
while(operator != 'E')
{
The semicolon ends the body of the while statement, in other words it behaves as if you would write this:
while(operator != 'E')
{
}
causing an infinite loop.
You need to remove the semi-colon at the end of while
You need to take into account both cases
So change
while(operator != 'E');
to
while(operator != 'E' && operator != 'e')
You have a classic bug in your while loop:
while (operator != 'E');
{
The ; after the condition is parsed as en empty statement, hence your while runs forever if operator is different from 'E'.
Using the classic Kernighan and Ritchie brace style makes this kind of bug obvious and much less likely to occur:
while (operator != 'E') {
Also note that you should exit your loop from the switch statement instead of testing for E in the while condition, this would allow for both e and E to be handled correctly (your statement operator == 'E'; is a no op, it should be written operator = 'E';. Also check the return value of scanf to avoid looping endlessly at end of file.
Here is an improved version:
#include <stdio.h>
int main(void) {
float n, content;
char operator;
int active = 1;
n = content = 0;
printf("Begin Calculations:\n");
while (active && scanf("%f %c", &n, &operator) == 2) {
switch (operator) {
case 's':
case 'S':
content = n;
printf("= %f\n", content);
break;
case '+':
content = content + n;
printf("= %f\n", content);
break;
case '-':
content = content - n;
printf("= %f\n", content);
break;
case '*':
content = content * n;
printf("= %f\n", content);
break;
case '/':
content = content / n;
printf("= %f\n", content);
break;
case 'e':
case 'E':
printf("End of calculations\n");
active = 0;
break;
default:
printf("Invalid input\n");
break;
}
}
return 0;
}
while(operator != 'E');
The correct syntax is while (...) { ... } without semicolon or do { ... } while (...); with.
printf("End of calculations\n");
operator == 'E';
The assignment operator is a single =. Change == into = and it should be fine.
You need to remove the semi-colon from while loop because semi-colon means end of statement so your program is not executing further
couple of things.
1- operator is a reserve word, you should change the variable name
2- (semicolon ;) after while()
Check update code:
#include <stdio.h>
int main(void)
{
float n, content;
char operator1;
n = content = 0;
operator1 = 'a';
printf("Begin Calculations:\n");
while(operator1 != 'E')
{
scanf("%c", &operator1);
switch(operator1)
{
case 's':
case 'S':
content = n;
printf("= %f\n", content);
break;
case '+':
content = content + n;
printf("= %f\n", content);
break;
case '-':
content = content - n;
printf("= %f\n", content);
break;
case '*':
content = content * n;
printf("= %f\n", content);
break;
case '/':
content = content / n;
printf("= %f\n", content);
break;
case 'e':
case 'E':
printf("End of calculations\n");
operator1 = 'E';
break;
default:
printf("Invalid input\n");
break;
}
}
return 0;
}
Related
Trying to solve a problem on kattis.com called "Bela", which requires some character comparison, but when i run my code the scanf() function does not get called the last couples time for the last couple iterations of the loop.
here is my code:
#include <stdio.h>
int main( void ) {`
char dom;
int n;
scanf("%d %c", &n, &dom);
n*=4;
int sum = 0;
for (int i = 0; i < n; i++) {
char num;
char suit;
scanf("%c%c", &num, &suit);
switch (num) {
case 'A':
sum += 11;
break;
case 'K':
sum += 4;
break;
case 'Q':
sum += 3;
break;
case 'J':
if (suit == dom) { sum +=20;}
else { sum += 2;}
break;
case 'T':
sum+=10;
break;
case '9':
if (suit == dom){sum+=14;}
break;
case '8':
break;
case '7':
break;
default:
continue;
}
}
printf("%d", sum);
return 0;
}
and when i run the with this test case program i get this:
:~$ ./a.out
^V
2 S
TH
9C
KS
QS
JS
TD3
AD
JH
:~$ TD
TD: command not found
:~$ AD
AD: command not found
:~$ JH
JH: command not found
why is the for loop not executing completely? Is there anyhting inherently wrong with my code that the switch case statement does not evaluate "TD", "AD", "JH"?
why is the for loop not executing completely?
Add printf("\nEnter:"); before second scanf check it. The loop execute fully but the scanf catches spaces.
So,
Add
while((ch=getchar()!='\n')&&ch!=EOF);
Before the second scanf or change second scanf to
scanf(" %c%c", &num, &suit);
^
This statements are ignore spaces(' ','\n',...)
I have a problem with calculator. I want to program a calculator, but it "works" with letters too. If I enter f.e letters "s" and "u", i get answer 0. How to repair that?
# include <stdio.h>
int main() {
char operator;
int a,b;
printf("Enter the operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two number and seperate them with space: ");
scanf("%lf %lf",&a, &b);
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("% 2lf - %.2lf = % 2lf",a, b, a - b);
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
printf("%.2lf / %.2lf = %.2lf",a, b, a / b);
break;
default:
printf("Error!");
}
return 0;
}
Sorry, if the question has been up here.
The link to answer is also appreciated!
Cheers!
I have made the corrections discussed in comments
#include <stdio.h>
int main(void) { // correct definition
char operator;
double a,b; // correct type
printf("Enter the operator (+, -, *, /): ");
if(scanf("%c", &operator) != 1) { // add error check
puts("Bad operator entered");
return 1;
}
printf("Enter two number and seperate them with space: ");
if(scanf("%lf %lf",&a, &b) != 2) { // add error check
puts("Bad value(s) entered");
return 1;
}
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("%.2lf - %.2lf = % 2lf",a, b, a - b); // corrected typo
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
printf("%.2lf / %.2lf = %.2lf",a, b, a / b);
break;
default:
printf("Error!");
}
return 0;
}
UPDATED:
i found my Ooldest code in library Folder maybe it helps you in that problem. This will definitely Work.
char operator;
printf("Enter the Operation in ( * , / , - , + )");
scanf("%s",&operator);
if(operator!='+' || operator!='-' || operator!='*' || operator!='/')
{
return 0;
}
I got it working. It was easier to do than I thought.
So the right code, I'll put comment to answer.
#include
int main(void) { // correct definition
char operator;
double a,b; // correct type
printf("Enter the operator (+, -, *, /): ");
if(scanf("%c", &operator) != 1) { // add error check
puts("Bad operator entered");
return 1;
}
printf("Enter two number and seperate them with space: ");
if(scanf("%lf %lf",&a, &b) != 2) { // add error check
puts("Bad value(s) entered");
return 1;
}
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("%.2lf - %.2lf = % 2lf",a, b, a - b); // corrected typo
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
if(b!=0){ //added an if-sentence
printf("%.2lf / %.2lf = %.2lf\n",a, b,
a / b);
}
else
printf("Can't divide by zero\n");
break;
default:
printf("Error!");
}
return 0;
}
Basically, I just put an if-sentence to case('/').
I am working on an accumulator that asks for different inputs and based on those inputs, updates values in an accumulator. My loop however, doesn't seem to run when I ask for a decimal, hexadecimal, or octal to be inputed. Could someone possibly take a look and give some suggestions to fix it? Thank you! Also Im suppose to somehow use a while loop in my print_menu() function that will check is the input is valid. Any suggestions?
#include <stdio.h>
#include <string.h>
short get_operand(char mode);
void print_acc(short acc);
char print_menu(void);
int main(void);
int main(){
char mode = 'D';
short acc = 8;
char input[10];
char option;
char valid_input[7] = "OHDCSQ";
while (mode != 'Q'){
print_acc(acc);
print_menu();
scanf("%s", &input);
printf("%s\n", input);
option = (char) toupper(input[0]);
switch(option){
case 'O':
mode = 'O';
printf("mode\n");
printf("Mode is Octal\n");
break;
case 'H':
mode = 'H';
printf("Mode is Hexadecimal\n");
break;
case 'D':
mode = 'D';
printf("Mode is Decimal\n");
break;
case 'C':
acc = 0;
break;
case 'S':
get_operand(mode);
if (mode == 'H'){
scanf("%hx", &acc);
printf("%hx", acc);
print_acc(acc);
}
else if (mode == 'O'){
scanf("%ho", &acc);
printf("%ho", acc);
print_acc(acc);
}
else{
scanf("%hd", &acc);
printf("%hd", acc);
print_acc(acc);
}
case 'Q':
mode = 'Q';
printf("\n");
break;
}
//return acc;
}
}
void print_acc(short acc){
printf("\n");
printf("****************************************\n");
printf("* Accumulator: *\n");
printf("* Hex : %04hx *\n", acc);
printf("* Octal : %08ho *\n", acc);
printf("* Decimal : %06hd *\n", acc);
printf("****************************************\n");
}
char print_menu(void){
printf("\n");
printf("Please Select one of the following options:\n");
printf("O Octal Mode\n");
printf("H Hecadecimal Mode\n");
printf("D Decimal Mode\n");
printf("\n");
printf("C Clear Accumulator\n");
printf("S Set Accumulator\n");
printf("\n");
printf("Q Quit\n");
printf("\n");
printf("Option: ");
}
short get_operand(char mode){
switch(mode){
case 'H':
printf("Enter Hex value:");
break;
case 'O':
printf("Enter Octal value:");
break;
default:
printf("Enter decimal value: ");
break;
}
return mode;
}
In the 'S' case where you read in a number, you forget to add a break statement at the end of the case. This results in the code falling through to the Q case which causes the loop to exit.
Add the break and the loop will continue as expected:
case 'S':
...
break;
case 'Q':
...
This is also incorrect:
scanf("%s", &input);
%s expects a char *, but you're passing the address of an array (a char (*)[10] to be presice). Pass in the array directly, which will decay to a pointer to the first element to yield the correct type:
scanf("%s", input);
Also, change print_menu and get_operand to return void, since you're not using the return value and in the former case failing to include one.
i have just entered a switch case code.. i don't understand why when i am pressing '1', it is still going to the default case always.
#include <stdio.h>
int main() {
char c = 0;
int x = 0, y = 0;
printf("Please write 2 numbers:\n");
scanf("%d %d", &x, &y);
printf("Please choose an action from the math menu:\n\n1.add\n2.sub\n");
scanf(" %c", &c);
switch (c)
{
case 1:
printf("%d + %d is %d\n", x, y, x+y);
break;
default: printf("Wrong value\n");
break;
}
return 0;
}
As c is declared as having character type then entered 1 and 2 are characters correspondingly '1' and '2'.
So write
switch (c)
{
case '1':
printf("%d + %d is %d\n", x, y, x+y);
break;
case '2':
printf("%d - %d is %d\n", x, y, x-y);
break;
default: printf("Wrong value\n");
break;
}
The character 0 to 9 are actually ascii values 48 to 57. switch( (int)(c-48) ) would work. The express (int)(c-48) changes the ascii digits to integers.
An alternative to the previous answer using character literals:
switch(c)
{
case '1':
...
break;
...
}
This allows you to even handle 'q' and the like.
When doing 'q', keep in mind the case sensitivity:
switch(c)
{
case 'q':
case 'Q':
... handle q
break;
}
In short: You are reading a char, treat it as a char.
My program's structure is like this:
main function has a menu (switch) between two other functions.
One of them is just a calculation and when it ends it goes back to this (main) menu.
Which is exactly what I want now (earlier I wanted to end the program after calculation and I had exit(0); in all cases.
But the other function is tricky because it starts another function (menu) and there are two options of calculations. One of them also has another switch.
The problem is when I edited codes which look like this by removing exit(0);
case 'H':
rhdp(0,n_hdp0, fw_vystup);
vyprazdni_buffer(); //buffer clearing
exit(0);
break;
It only works for the simple calculation but deeper parts of the program only go one step back...
Any possible solutions? Thanks in advance.
here is more of a code
void nhdp_menu(float cislo, FILE **fw_vystup)
{
char c;
float y, n_hdp0 = 0.0f, n_hdp1 = 0.0f;
do {
printf("Zadejte nominalni hruby domaci produkt daneho roku: ");
zadani_cisla(&cislo);
n_hdp1 = cislo;
} while (n_hdp1 <= 0);
do {
printf("Zadejte nominalni hruby domaci produkt predesleho roku: ");
zadani_cisla(&cislo);
n_hdp0 = cislo;
} while (n_hdp0 <= 0);
y = (n_hdp1 - n_hdp0) / n_hdp0 * 100;
printf("Tempo rustu nominalniho HDP je %f procent.\n", y);
zapis(fw_vystup, "Nominalni HDP0 = %f ; Nominalni HDP1 = %f ; Tempo rustu nominalniho HDP je %f procent.\n", n_hdp0, n_hdp1, y);
do {
printf("Dodatecne muzete take zjistit tempo rustu REALNEHO HDP:\n");
printf("Pokud znate deflator HDP v danem roce - zadejte D.\n");
printf("Pokud znate primo realne HDP v danem roce - zadejte H.\n");
vyprazdni_buffer();
scanf("%c", &c);
switch (c) { //this is the last (deepest) switch
case 'd':
case 'D':
rhdp_ipd(0, n_hdp0, n_hdp1, fw_vystup);
vyprazdni_buffer();
//exit(0);
break;
case 'h':
case 'H':
rhdp(0,n_hdp0, fw_vystup);
vyprazdni_buffer();
//exit(0);
break;
case 'k':
case 'K':
printf("Konec programu.\n");
break;
default:
printf("Neznama volba.\n");
break;
}
} while (c != 'k' && c != 'K');
return;
}
void tempo_menu(n_hdp0)
{
FILE *fw_vystup;
char c;
do {
printf("Vyberte si, v jakych cenach chcete HDP uvadet.\nPro nominalni zadejte N.\nPro realne zadejte R.\n");
scanf("%c", &c);
vyprazdni_buffer();
switch (c) {
case 'N':
case 'n':
nhdp_menu(0, &fw_vystup); //this here is starting another menu
vyprazdni_buffer();
//exit(0);
break;
case 'R':
case 'r':
rhdp(0, 0, &fw_vystup);
vyprazdni_buffer();
//exit(0);
break;
case 'k':
case 'K':
printf("Konec programu.\n");
break;
default:
printf("Neznama volba.\n");
break;
}
} while (c != 'k' && c != 'K');
return;
}
int main(void)
{
char c;
FILE *fw_vystup;
do {
printf("Zadejte D pro vypocet deflatoru HDP nebo T pro vypocet tempa rustu HDP: ");
scanf("%c", &c);
vyprazdni_buffer();
switch (c) {
case 'd':
case 'D':
deflator(0, &fw_vystup); //for this function everything goes well
// exit(0);
vyprazdni_buffer();
break;
case 't':
case 'T':
tempo_menu();
vyprazdni_buffer();
// exit(0);
break;
case 'k':
case 'K':
printf("Konec programu.\n");
break;
default:
printf("Neznama volba.\n");
break;
}
} while (c != 'k' && c != 'K');
return 0;
}
EDIT:
So this is assuming you're put return in all the case statements because this is the behavior you want.
The problem with main not printing until you press some keys. Try using fflush(stdout) in your main function:
int main(void)
{
char c;
FILE *fw_vystup;
do {
printf("Zadejte D pro vypocet deflatoru HDP nebo T pro vypocet tempa rustu HDP: ");
scanf("%c", &c);
vyprazdni_buffer();
switch (c) {
case 'd':
case 'D':
deflator(0, &fw_vystup); //for this function everything goes well
vyprazdni_buffer();
break;
case 't':
case 'T':
tempo_menu();
vyprazdni_buffer();
break;
case 'k':
case 'K':
printf("Konec programu.\n");
break;
default:
printf("Neznama volba.\n");
break;
}
fflush(stdout); // <--- right here.
} while (c != 'k' && c != 'K');
return 0;
}