Variable not Updating, While Loop not working - c

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.

Related

Why is there an infinite loop when I do not enter a number?

When I enter the letter 'q' as grade, it runs infinitely.
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int grade;
bool flag = true;
while (flag) {
puts("-----------------------------"); // comment
printf("What's your grade out of 10? ");
scanf(" %d", &grade);
switch (grade) {
case 10:
case 9:
case 8:
case 7:
case 6:
printf("Pass\n");
break;
case 5:
printf("Fail\n");
break;
case 4:
printf("Fail\n");
break;
case 3:
printf("Fail\n");
break;
case 2:
printf("Fail\n");
break;
case 1:
printf("Fail\n");
break;
case 0:
printf("Fail\n");
break;
default:
printf("Illegal Grade\n");
flag = false;
break;
}
}
return 0;
}
scanf(" %d",&grade);
It scans int in string. "q" is not int. When you enter "q", value of the variable grade left unchanged. You must check returned value of scanf to validate number of filled placeholders.
if (scanf(" %d",&grade) != 1) {
printf("Illegal Grade\n");
exit(1); // or break
}
Other parts are ok.
scanf(" %d", &grade); fails when you type something that cannot be parsed as into an integer. grade is not modified, so it is uninitialized if the conversion error happens immediately and the behavior is undefined, otherwise you get the same value and behavior as the previous time.
The offending input stays in the input stream, so the same thing happens when the code executes again in the while loop, hence the infinite loop.
You want to test if the conversion was successful and discard the input if not:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int res, c, grade;
bool flag = true;
while (flag) {
puts("-----------------------------"); // comment
printf("What's your grade out of 10? ");
res = scanf("%d", &grade);
if (res == EOF)
break;
if (res == 0) {
printf("Invalid input\n");
/* discard the offending line of input */
while ((c = getchar()) != EOF && c != '\n')
continue;
/* try again */
continue;
}
switch (grade) {
case 10:
case 9:
case 8:
case 7:
case 6:
printf("Pass\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Fail\n");
break;
default:
printf("Illegal Grade\n");
flag = false;
break;
}
}
return 0;
}

Having troubles with nested while loops

The goal is to assign the average to different players based on their uniform number. The problem is that it keeps skipping the second printf and the characters from the switch statement aren't working. I'm sure it's a pretty simple error on my part, but I just can't seem to find it.
int main(){
float ab;
float hits;
int un;
char pa;
printf("Please enter the player number, or -1 to exit. \n");
scanf("%d%*c \n", &un);
while( un!= -1)
{
printf("Please enter either an H for a hit or an O for a out, enter E to stop. \n");
scanf("%c%*c", &pa);
while(pa != 'E')
{
switch (pa)
{
case 'h':
case 'H':
ab += 1;
hits +=1;
break;
case 'o':
case 'O':
ab+=1;
break;
default:
printf("Error: Please insert an O or H \n");
break;
}
float average = (ab/hits);
printf("Player %d's score is equal to: %d \n", un, average);
printf("Please enter the player number, or -1 to exit. \n");
scanf("%d%*c \n", &un);
}
}
return 0;
}
Your loop nesting wasn't quite correct, your scanf calls would hang, you needed to preinitialize ab and hits, and your final printf had an incorrect format.
Here's the corrected code [please pardon the gratuitous style cleanup]:
#include <stdio.h>
int
main()
{
float ab;
float hits;
int un;
char pa;
while (1) {
printf("Please enter the player number, or -1 to exit.\n");
#if 0
scanf("%d%*c \n", &un);
#else
scanf(" %d", &un);
#endif
if (un == -1)
break;
ab = 0;
hits = 0;
printf("Please enter either an H for a hit or an O for a out, enter E to stop.\n");
while (1) {
#if 0
scanf("%c%*c", &pa);
#else
scanf(" %c", &pa);
#endif
if ((pa == 'E') || (pa == 'e'))
break;
switch (pa) {
case 'h':
case 'H':
ab += 1;
hits += 1;
break;
case 'o':
case 'O':
ab += 1;
break;
default:
printf("Error: Please insert an O or H\n");
break;
}
}
float average = (ab / hits);
#if 0
printf("Player %d's score is equal to: %d\n", un, average);
#else
printf("Player %d's score is equal to: %g\n", un, average);
#endif
}
return 0;
}

Beginners switch case action is always default

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.

While loop - changing string variable

As a newbie to c programming (I've only had experience in visual basic), I'm not entirely sure how a while loop with a changing string variable in its condition statement should function.
The following code is a simple calculator that I was making that allows the user to input an operation and two numbers, then output the respective result. I'am trying to code in a while loop that continually repeats the procedure until the user decides to exit it. However it seems that the line scanf("%c", &quit); isn't affecting the while loop condition statement.
#include <stdio.h>
int main() {
float num1, num2;
char operation;
char quit = "n";
while (quit = "n"){
printf("Enter an operator (+, -, *, /) \n");
scanf(" %c", &operation);
printf("Enter the numbers you wish to carry out the operation on \n");
scanf("%f %f", &num1, &num2);
switch(operation) {
case '+':
printf("%f\n", num1+num2);
break;
case '-':
printf("%f\n", num1-num2);
break;
case '*':
printf("%f\n", num1*num2);
break;
case '/':
printf("%f\n", num1/num2);
break;
}
printf("Would you like quit the program, is so enter 'y' \n");
scanf("%c", &quit);
}
return 0;
}
Thanks for all your help in advance.
You could do like this
#include <stdio.h>
int main() {
float num1, num2;
char operation;
char quit = 'n';
//while (quit = "n") //
while (quit!= 'y')
{
printf("Enter an operator (+, -, *, /) \n");
scanf(" %c", &operation);
printf("Enter the numbers you wish to carry out the operation on \n");
scanf("%f %f", &num1, &num2);
switch(operation) {
case '+':
printf("%f\n", num1+num2);
break;
case '-':
printf("%f\n", num1-num2);
break;
case '*':
printf("%f\n", num1*num2);
break;
case '/':
printf("%f\n", num1/num2);
break;
}
printf("Would you like quit the program, is so enter 'y' \n");
scanf("%c", &quit);
}
return 0;
}
replace while (quit = "n") with while (quit! = 'y')
That's because you're assigning the value of the quit variable in your while loop, instead of checking for its value.
Use == for =
while(quit == "n"){...}

How to have a C program respond to a letter and spit out something else?

I can't seem to get this program to compile.
I keep getting the error:
'Ammonia' undeclared 'Carbon_Monoxide' undeclared
and so on. Am I using the right function with switch?
/*This program will report the content of a compressed-gas cylinder based on the first letter of the cylinder's color.*/
#include <stdio.h>
int main (void)
{
int x;
char o, b, y, g;
int pause;
o = Ammonia;
b = Carbon_Monoxide;
y = Hydrogen;
g = Oxygen;
printf(" Enter a character representing the observed color of the cylinder \n" );
scanf("%d", &x);
switch (x)
{
case 'o': printf("The content is Ammonia\n");
case 'b': printf("The content is Carbon Monoxide\n");
case 'y': printf("The content is Hydrogen\n");
case 'g': printf("The content is Oxygen\n");
default: printf("Character out of range \n");
}
printf("After Switch \n");
printf("Enter new character to continue \n");
scanf("%d", &pause);
return 0;
}
It has nothing to do with your switch statement, but you will probably have to puzzle over the meaning of these four lines:
o = Ammonia;
b = Carbon_Monoxide;
y = Hydrogen;
g = Oxygen;
You don't use the variables thus defined anywhere, and the symbols "Ammonia", "Carbon_Monoxide" and so on are not defined - this is the cause of the error you are seeing.
Since this is homework, I don't want to give you the answer straight, but look at what you're doing with those chars (o, b, y, g) and ask yourself if it makes sense.
Also, on the switch statement, I'm pretty sure you need a break; after each case, else it will print each case's statement
try:
#include <stdio.h>
int main (void)
{
char x;
int pause;
printf(" Enter a character representing the observed color of the cylinder \n" );
scanf("%c", &x);
while(x){
switch (x)
{
case 'o': printf("The content is Ammonia\n"); break;
case 'b': printf("The content is Carbon Monoxide\n"); break;
case 'y': printf("The content is Hydrogen\n"); break;
case 'g': printf("The content is Oxygen\n"); break;
default: printf("Character out of range \n");
}
printf("After Switch \n");
printf("Enter new character to continue \n");
scanf(" %c", &x);
if(x == 'q'){
break;
}
}
return 0;
}

Resources