Code fails at case '0' - I don't understand why - c

Here is a minimal form of the code emphasizing the issue I have.
Code fails at "exit"(case '0') - program simply crashes. I suspect it is related to the while loop.
The issue occurs no matter what character i choose for the exit case (instead of '0').
#include <stdio.h>
void main()
{
int run=1;
char menu_option;
while (run==1)
{
printf("Choose case:\n");
scanf ("%s", &menu_option);
switch (menu_option) {
case '1':
printf("1");
break;
case '2':
printf("2");
break;
case '0':
run=0;
break;
default:
printf("Wrong input, try again\n");
}
}
}

menu_option is not a string, so %s is the wrong format specifier. You need %c, prefixed with a space to prevent whitespace (including newline) being interpreted as valid character input.
scanf (" %c", &menu_option);

Related

Basic C - Switch cases duplication

I am working on a project, where you answer a char, and if it is not one of the 4 answers, it tells you to try again. If it is not the correct one of the 4, it stops running. Here is a snippit.
#include <stdio.h>
#include <stdbool.h>
bool switchCheck = true;
char answer;
printf("A. English\nB. French\nC. Spanish\nD. German\n");
do{
scanf("%c\n", &answer);
switch (answer){
case 'C':
printf("Very nice ");
break;
case 'B':
case 'A':
case 'D':
printf("Sorry! Incorrect. Code Ends\n");
switchCheck =false;
break;
default:
printf("Try Again\n");
}
}while(switchCheck==true);
For some reason, when I input A, B, or D, it first prints the result for default, and if I do it again immediately afterward, it gives me the right input. Any help?
Thanks!
You are using scanf like
scanf("%c\n", &answer);
Instead use
scanf( " %c", &answer );
See the blank before the conversion specifier %c. It allows to skip white spaces.

How Terminate the Program on Pressing Enter key in C?

i am making a small project in which I have to convert different values to different bases like 10,8,16.But the problem is that I want to run the program till the user press 6 but if user hit Enter key then too it is waiting for the input rather than simply terminating. I'm using C11 version of C on online compiler.
and here's my code.
#include "ConvertInBackgnd"
#include<stdio.h>
int main() {
int choice;
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
l1: printf("Input your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
dec_bin();
break;
case 2:
bin_dec();
break;
case 3:
dec_octal();
break;
case 4:
octal_dec();
break;
case 5:
dec_hex();
break;
case 6:
goto l1;
default:
printf("Invalid choice.");
break;
}
printf("Input 6 for reconverting the values.");
scanf("%d", &choice);
if (choice == 6) {
goto l1;
} else
return 0;
return 0;
}
I have made a separate file in which I have made functions and I thought it isnot necessary to put that code here too.
Consider using fgets to take input into a character array.
If needed, the input can be parsed with sscanf, strtol or others.
#include<stdio.h>
int main() {
char line[100] = "";
do {
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
printf("Input your choice : ");
fgets ( line, sizeof line, stdin);
switch ( line[0]) {
case '1':
printf ( "dec_bin()\n");
break;
case '2':
printf ( "bin_dec()\n");
break;
case '3':
printf ( "dec_octal()\n");
break;
case '4':
printf ( "octal_dec()\n");
break;
case '5':
printf ( "dec_hex()\n");
break;
case '6':
case '\n':
break;
default:
printf("Invalid choice.");
break;
}
if ( line[0] != '\n') {
printf("Input 6 for reconverting the values.");
fgets ( line, sizeof line, stdin);
}
} while ( line[0] == '6');
return 0;
}
To solve the enter problem:
scanf("%d", &choice)
Right now you are taking int value, try with char value and match the enter key with it. Then you'll be able to do what you are trying to do.
Ok, So I wanted to terminate the program if Enter key is pressed. So I was first a newbie then I realized that itsnot a big deal and to do so I just need to take a char as Input and then check that if that char input is enter key or not.
Its a sample code to terminate the program after pressing enter key.
char line;
scanf("%c",&line);
if(line=='\n')
return 0;
else
// your other code
But if your program doesnot take input then you should clear the buffer before the above provided code by adding just this single line before the above code.
while(getchar()!='\n');

C. after using scanf() with the list of allowed characters, can't get the value of the entered character

I've found out that you could write the list of characters that are (not)allowed as an input when using scanf().
I need a user to type one of the following letters: d, f, r, k, c
So what i did is the following, and it works actually exactly the way i want it to. it doesn't let the program go further until one of the allowed letters is eventually pressed:
scanf ("%[^cfrdk]", &skala);
after that i want to check which of those five letter was actually entered, and here i get the whole problem. i don't get what exactly happens to the variable skala but its value is obviously not the entered letter. as i try to print it, it prints nothing. The switch-case after that also always goes by default.
here is the whole code:
int main()
{
char skala;
float inval,cels, fahr, kelvin, rankine, delis;
printf("Choose the Skala. Enter:\n`C` for Celsius"
" \n`F` for Fahrenheit \n`D` for Delisle \n`K` for Kelvin \n`R` for Rankine"
" \n Enter the letter here —> ");
scanf ("%[^cfrdk]", &skala);
getchar();
//printf("You have entered correctly. %c", &skala); PRINTS NOTHING
switch (skala){
case 'c': printf("You've chosen Celsius\n");
break;
case 'f': printf("You've chosen Fahrenheit\n");
break;
case 'r': printf("You've chosen Rankine\n");
break;
case 'd': printf("You've chosen Delisle\n");
break;
case 'k': printf("You've chosen Kelvin\n");
break;
default:printf("ERROR: wrong input\n");
break;
}
printf ("Enter a value to be converted = ");
scanf("%f", &inval);
return 0;
}`
who can explain it what exactly happens to the variable in scanf when using the list of allowed characters. And what are the ways of solving the problem?
The do/while loop will repeat until a letter in the set of valid letters is input.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char skala;
char valid[] = "cfdkr";
float inval,cels, fahr, kelvin, rankine, delis;
int result = 0;
int clean = 0;
printf("Choose the Skala. Enter:\n`C` for Celsius"
" \n`F` for Fahrenheit \n`D` for Delisle \n`K` for Kelvin \n`R` for Rankine"
" \n Enter the letter here —> ");
do {
if ( ( result = scanf (" %c", &skala)) != 1) {
if ( result == EOF) {
fprintf ( stderr, "problem getting input\n");
return 1;
}
}
if (strchr ( valid, skala) == NULL) {
printf ( "enter your choice of %s\n", valid);
result = 0;
}
} while ( result != 1);
switch (skala){
case 'c': printf("You've chosen Celsius\n");
break;
case 'f': printf("You've chosen Fahrenheit\n");
break;
case 'r': printf("You've chosen Rankine\n");
break;
case 'd': printf("You've chosen Delisle\n");
break;
case 'k': printf("You've chosen Kelvin\n");
break;
default:printf("ERROR: wrong input\n");
break;
}
do {
printf ("Enter a value to be converted = ");
if ( ( result = scanf("%f", &inval)) != 1) {
while ( clean = getchar ( )) != '\n') {
if ( clean == EOF) {
fprintf ( stderr, "problem getting input\n");
return 1;
}
}
}
} while ( result != 1);
return 0;
}
I need a user to type one of the following letters: d, f, r, k, c
Code cannot control what the user types. Code needs to cope with unexpected input.
The below is bad code. If scanf() does encounter some non-cfrdk, it will save 1 or more of those characters into skala and then append a null character. skala being only a char, is the wrong type for reading strings - the type expected by %[]. Result: Undefined behavior (UB).
If use does type a cfrdk, then scanf ("%[^cfrdk]", &skala); will read nothing into skalla and return 0.
scanf ("%[^cfrdk]", &skala);
Better to simply read all user input. Be sure to handle '\n'
switch (getchar()){
case 'c': printf("You've chosen Celsius\n");
break;
case 'f': printf("You've chosen Fahrenheit\n");
break;
case 'r': printf("You've chosen Rankine\n");
break;
case 'd': printf("You've chosen Delisle\n");
break;
case 'k': printf("You've chosen Kelvin\n");
break;
case '\n': // ignore
break;
case EOF: // input is closed
return -1;
default: printf("ERROR: wrong input\n");
// break;
}
Even better as suggested by #hyde, read a line of user input with fgets() and then validate the input.
char buf[80];
if (fgets(buf, sizeof buf, stdin) == NULL) {
// Handle End-Of-File or Error
return -1;
}
char scale[2] = { 0 };
// Check for valid initial character, additional checks possible
if (sscanf(buf, "%1[cfrdk]") != 1) Handle_Bad_Input(buf);
else {
switch (scale[0]) {
...

scanf asking for two values instead of one [duplicate]

This question already has answers here:
scanf() curious behaviour!
(3 answers)
Closed 8 years ago.
When I compile this code, it leads to scanf asking for a value twice when I pick choice A. What am I missing here?
This isn't the first time this is encountered, so I'm suspecting I'm failing to grasp something rather fundamental with scanf.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
printf("1. 'enter 'A' for this choice\n");
printf("2. 'enter 'B' for this choice\n");
printf("3. 'enter 'C' for this choice\n");
scanf("%c", &choice);
switch (choice)
{
case 'A':
{
int a =0;
printf("you've chosen menu A\n");
printf("enter a number\n");
scanf("%d\n", &a);
printf("%d\n", a);
}
break;
case 'B':
printf("you've chosen B\n");
break;
case 'C':
printf("you've chosen C\n");
break;
default:
printf("your choice is invalid\n!");
break;
}
return 0;
}
scanf("%d\n", &a); should be scanf("%d", &a);
Also read Related question.
In former case after reading an integer and storing into a, scanf's argument string is not exhausted. Looking at \n, scanf would consume all the whitespaces (newline, tab, spaced etc) it sees (And will remain blocked) until it encounters a non-whitespace character. On encountering a non-whitespace character scanf would return.
Learning: Don't use space, newline etc as trailing character in scanf. If the space character is in the beginning of argument string, scanf may still skip any number of white space characters including zero characters. But when whitespace is a trailing characters, it would eat your new line character also unless you type a non-whitespace character and hit return key.
Simply remove the newline character from scanf("%d\n", &a); and it will not ask to enter a value twice
scanf("%d", &a);
Remove a newline character while scanning
// the trailing '\n' in the scanf format string
// is what is causing the dual inputs
// the returned value from I/O statements (I.E. scanf)
// needs to be checked to assure operation was successful
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
printf("1. 'enter 'A' for this choice\n");
printf("2. 'enter 'B' for this choice\n");
printf("3. 'enter 'C' for this choice\n");
// note
// leading ' ' in format string to consume leading white space
// and no trailing '\n'
if( 1 != scanf(" %c", &choice) )
{ // then, scanf failed
// handle error condition
perror("scanf failed for choice");
exit(EXIT_FAILURE);
}
// implied else, scanf successful
switch (choice)
{
case 'A':
{ // braces needed due to variable declaration
int a = 0; // corrected ':' to ';'
printf("you've chosen menu A\n");
printf("enter a number\n");
// note
// leading ' ' in format string to consume leading white space
// and no trailing '\n'
if( 1 != scanf(" %d", &a) )
{ // then scanf failed
// handle error condition
perror("scanf failed for number");
exit(EXIT_FAILURE);
}
// implied else, scanf successful
printf("%d\n", a);
}
break;
case 'B':
printf("you've chosen B\n");
break;
case 'C':
printf("you've chosen C\n");
break;
default:
printf("your choice is invalid\n!");
break;
} // end switch
return 0;
} // end function: main

switch statement creating infinite loop

I am writing a piece of code and in one part of my code I am using a switch statement in C language. if I press n it exits correctly if I press y it will infinite loop the default statement until I press control c. what am I doing wrong here. been changing the while statement but can't find the right one.
int main()
{
char ans;
printf("DO you want to continue?");
scanf("%c", &ans);
do
{
switch(ans)
{
case 'y':
some stuff...
printf("DO you want to continue?");
scanf("%c", &ans);
break;
case'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
return 0;
}
When you press enter, the linefeed character \n is added to the input stream. Your code does not anticipate this, because switch(ans) only handles y, n or “everything else” (which includes the linefeed character).
To fix this, allow scanf to ignore any preceding whitespace by changing your format string to " %c" instead, e.g.
scanf(" %c", &ans);
// ^ space character inserted here
I think it would make more sense to move the scanf call to inside the loop, like this:
int main()
{
char ans;
do
{
printf("DO you want to continue?");
if (scanf(" %c", &ans) != 1)
break;
switch(ans)
{
case 'y':
// some stuff...
break;
case 'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
}
Don't forget to always check the result of scanf(). It will return the number of items successfully scanned (in your case, you want it to return 1). If it returns 0 or a negative number, then another problem has occurred.

Resources