I am new at C and am trying to create my first menu! But whenever the user inputs 1 and enter the default option appears and reload the menu. Although when 4 and enter are hit the default option also appears but the menu is successfully exited.
void begin_menu(void)
{
int choice;
do
{
printf("English Draughts - Main Menu\n\n");
printf("1. Play Game\n");
printf("2. Display Winners\n");
printf("3. Reset Scoreboard\n");
printf("4. Quit\n");
scanf("%d",&choice);
switch (choice)
{
case '1' : play();
break;
case '2' : /*write function to do here */
break;
case '3' : /*write function to do here */
break;
case '4' :
printf("Goodbye!\n");
exit(0);
break;
default:
printf("Please insert a correct choice.\n");
break;
}
} while (choice != 4);
}
void play(void)
{
while(end != "n");
{
printf("Player Names\n\n");
printf("Enter name for first player:\n");
scanf("%s",&player_one);
printf("Enter name for second player:\n");
scanf("%s",&player_two);
printf("Begin?(y to start, n to quit)\n");
scanf("%c",&end);
}
return;
}
Thanks everyone, but I have the problem that if play() is called.. ie 1 is entered.. the console just looks for input and doesn't print the function information at all.
'1'and 1 are not the same thing
The first one is an ascii character, the second one is a number.
You can lookup the value of '1' in the ascii table and see that it is 49, which does not equal 1.
Try entering 49 in your console, just for fun :)
You are evaluating strings instead of integers.
You defined the choice variable as an integer, so comparisons must be with integers to. Remove the ' around your numbers inside your switch statement and it should work fine.
You are having choice as integer data type.
int choice;
But in switch case you are checking for character constants. So it leads to default case always. Because '1' and 1 are not same!
Try the below changes-
switch (choice)
{
case 1 : play();
break;
case 2 : /*write function to do here */
break;
case 3 : /*write function to do here */
break;
case 4 : printf("Goodbye!\n");
exit(0);
break;
default: printf("Please insert a correct choice.\n");
break;
}
You have case '1' instead of case 1
'1' is an ascii character and 1 is an integer.
As others mentioned, '1' and 1 are not the same. '1' has a decimal value of 49. You can fix your code by:
changing choice to be type of char and then tell scanf to expect format of %c, not %d
or you can change your switch cases to use decimal values.
Switch cases accepts only integer constants. All of the cases are evaluated to integers, hence your code works. Note that switch cases won't work with string literals. If you would type "1" instead of '1' you would get a compiler error.
Related
I am new to C and am writing a simple code of converting temperatures. The code is still incomplete but still should give me some output
#include<stdio.h>
void main()
{
float temp;
char choice;
printf("\n 1. Celcius to Farenhite\n 2. Farenhite to Celcius\n What do you want to convert from? : ");
scanf("%c", &choice);
switch (choice)
{
case 1:
printf("Enter temperature in Celcius: ", temp );
scanf("%f", &temp);
break;
case 2:
printf("Enter temperature in Farenhite: ", temp);
scanf("%f", &temp);
break;
default:
printf("Invalid Choice");
break;
}
}
When I run this it asks "what do you want to convert from?" and shows the options. But when I enter 1 or 2, it directly prints and shows "Invalid Choice".
Pls tell me what's wrong :(
1 is 'int' and not a char.
1 and '1' are different.
This is the edited code
#include<stdio.h>
void main()
{
float temp;
char choice;
printf("\n 1. Celcius to Farenhite\n 2. Farenhite to Celcius\n What do you want to convert from? : ");
scanf("%c", &choice);
switch (choice)
{
case '1':
printf("Enter temperature in Celcius: ", temp );
scanf("%f", &temp);
break;
case '2':
printf("Enter temperature in Farenhite: ", temp);
scanf("%f", &temp);
break;
default:
printf("Invalid Choice");
break;
}
}
The number one is not the same as the digit "1". You are entering the character "1" and your switch statement is checking for the number one.
The number one is how many hearts I have. It can be written with the digit '1' but any number of other ways.
The digit '1' is a character. It is sometimes use to represent the number one but can also be used for other things. A variable of type char can hold the digit 1 since digits are characters.
Your switch statement is checking for the number one. You want to check for the character 1.
'1' is a character, whereas 1 is an integer. Your switch statement can't find a case to match with, hence it goes to default.
Is that the complete code? You're not converting anything here, you're only asking the user for the temperature and storing it in a variable.
OT: Indent properly, your code is messy and difficult to read. And do not use scanf for taking input. You may want to check out this link http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html.
This is a common misunderstanding for novices and occasional typo for experienced programmers(*).
1 means "the integer value one" (it is the integer literal for the value of 1).
Assuming your on an ASCII compatible platform(**) that is the character with ASCII code 1 (the non-printing character called Start of Header - SOH).
The ASCII Code for the character 1 is actually 49. But you should write:
case '1':
Because those apostrophes identify the 1 as the character representing 1 not the numeric value of 1.
The compiler will interpret '1' as actually meaning character of 1 meaning the (codepoint) value of 49.
In C char has a deeply dual role as a numeric type and as the smallest unit of text and accidental mixing of those roles causes endless confusion.
Arguably char has 3 roles. The smallest arithmetic type, the smallest unit of text (a character) and the unit of addressable memory (byte).
There are historical reasons why those roles are conflated in C.
(*) But I can't find a good answer for it even though there should be thousands of times this has been asked.
(**) C does not specify a character set but if you working on a platform that isn't ASCII compatible you will know about it. Unless you've found something in your Grandparent's basement and they're sadly not around to explain it. This footnote exists for the likely comments to the effect that C doesn't specify a character set.
Your program reads a byte from stdin and compares that to the values 1 and 2. It is unlikely the user can type these byte values as they correspond to control characters CtrlA and CtrlB1. The byte values representing the digits 1 and 2 typed by the user are noted in C as '1' and '2'. These are called character constants and are int values for the encoding of the corresponding characters.
Furthermore, you should:
indent your code more consistently.
define main with a return type int
test the return value of scanf()
fix the spelling of Fahrenheit, named after German physicist Daniel Gabriel Fahrenheit and Celsius, named after Swedish astronomer Anders Celsius.
1: From a unix terminal, one can actually enter these byte values by hitting CtrlV CtrlA and CtrlV CtrlB, respectively, followed by Enter.
Here is a modified version:
#include <stdio.h>
int main() {
float temp;
char choice;
printf(" 1. Celsius to Fahrenheit\n"
" 2. Fahrenheit to Celsius\n"
" What do you want to convert from? ");
if (scanf(" %c", &choice) != 1)
return 1;
switch (choice) {
case '1':
printf("Enter temperature in Celsius: ", temp);
if (scanf("%f", &temp) != 1)
return 1;
printf("%g degrees Celsius is %g degrees Fahrenheit\n",
temp, 32 + temp * 9 / 5);
break;
case '2':
printf("Enter temperature in Fahrenheit: ", temp);
if (scanf("%f", &temp) != 1)
return 1;
printf("%g degrees Fahrenheit is %g degrees Celsius\n",
temp, (temp - 32) * 5 / 9);
break;
default:
printf("Invalid choice\n");
break;
}
return 0;
}
I'm trying to do this loop in C, where you would press enter and be in it and you either press 0 to exit or 3 to continue in it. But somehow the Switch commands are no being activated. Note that there is a different messages on each of them that is supposed to differentiate them from the other outcomes. Can someone help me understand the problem with this code?`Note: the code is obviously within int main().
int I = 1;
printf("Press enter to start the loop...");
getchar();
do
{
printf("\nYou are in a LOOP. Would you like to stay in it, or leave it? \nPress 0 to leave the loop or press 3 to stay in it: ");
scanf_s("%d", &I);
getchar();
switch (I)
{
case'3':
printf("\nYou are STILL inside the LOOP. Press 0 to leave it or press 3 to stay in it: ");
getchar();
break;
case'0':
printf("\nExiting the LOOP...");
break;
default:
printf("\nPlease, enter a valid command...: ");
if (scanf_s("%d", &I) != 3 || scanf_s("%d", &I) != 0);
{
fflush(stdin);
}
break;
}
while (I != 0);
printf("\nCongratulations! You are OUT of the LOOP!");
As others have pointed out, you are reading in an integer with scanf_s(), but comparing against a character literal inside the switch statement.
switch'3': should be written as switch 3: (using an integer literal instead). Same goes for the 0 case.
Also, your example is missing a curly brace } before while(I != 0);.
It is also worth mentioning that scanf_s() "returns the number of fields successfully converted and assigned" (from https://msdn.microsoft.com/en-us/library/w40768et.aspx). That is, your scanf_s() call in the default switch case will only ever return 0 or 1 when reading in a single integer (or EOF on error).
I have a function as part of a larger program to determine the quantity of products sold on each day of the previous week. Here is the function that performs the case switch:
unsigned int switchfn()
{
int productNumber; // product 1 through 5
// only while product 1 through 5 is being entered.
while ((scanf("%d", &productNumber)) != EOF) {
// gather product data
switch (productNumber) {
case '1': // product one
++productOne;
break;
case '2': // product two
++productTwo;
break;
case '3': // product three
++productThree;
break;
case '4': // product four
++productFour;
break;
case '5': // product five
++productFive;
break;
case '\n': // ignore new line
case '\t': // ignore tab
case ' ': // ignore space
break;
default: // catch all other characters
printf("%s", "No such product exists.");
puts(" Please enter a valid product number.");
break;
}
}
return 0;
}
However, when the program runs, it always jumps to the default, even when entering numbers 1 through 5. Is this an issue with what scanf() is returning?
You appear to be getting confused between integers and ASCII digits. You're performing formatted extraction, but inspecting productNumber as if it were the actual ASCII character found in the input.
Remember, '1' is actually 49.
Since you want to cover cases like '\n' too, read into a char with %c instead. Then the extraction operation won't perform the formatting conversion for you as it is now, and your character literal comparisons will be correct.
Case '1' - at this moment you are asking compiler to check did you enter a character '1' - his ASCII value is 49 and that's the reason why he is just skipping to default case. Try to input " %c"
scanf("%d", &productNumber) get productNumber is a interger.
But case '1' : '1' is a char and his ASCII value is 49 and so every time you input a interger, there is no match case just skipping to default case. u can input " %c" to get a char.
Since your scanf function is referencing an integer, you merely have to switch your cases to integers:
case 1:
//your logic
break;
case 2:
//your logic
break;
scanf("%ld",&l);
printf ("l=%ld",l);
switch (l)
{
case'1':
XOR(&matrix1[10],&matrix2[10],m);
break;
case'2':
AND(&matrix1[10],&matrix2[10],m);
break;
default:
printf("\n\t\tWrong input");
}
When the program reaches switch, no matter what I enter (whether it's wrong or right), the program keeps showing the massage (Wrong input), though I've entered a right number (1 or 2).
Change your case labels from
case'1':
...
case'2':
...
to
case 1:
...
case 2:
...
Explanation: your switch value is an integer, not a character, hence you need integer constants for your case labels, not character constants.
Your case should be case 1 and not case '1'.
'1' != 1
Note: '1' is nearly 60 or something like that, 'cause single quotes mean "using char" (or it's ASCII code). Try removing 'em from your switch cases:
scanf("%ld",&l); printf ("l=%ld",l); switch (l) { case 1: XOR(&matrix1[10],&matrix2[10],m); break; case 2: AND(&matrix1[10],&matrix2[10],m); break; default: printf("\n\t\tWrong input"); }
Or you can change your input from numeric to char:
scanf("%c", &l);
But you aren't reading a character but your cases are characters. Re-write as follows:
switch (l)
{
case 1:
XOR(&matrix1[10],&matrix2[10],m);
break;
case 2:
AND(&matrix1[10],&matrix2[10],m);
break;
default:
printf("\n\t\tWrong input");
}
'1' and 1 are not the same.
Because your switch is relying on an integer. Whereas you're taking in a string. You'll need to run l through atoi first.
'1' is a char, the ASCII representation of the digit 1. Use plain 1 instead.
case 1:
/*...*/
break;
That's because:
case '1':
is not the same as:
case 1:
The second one is the one you seem to be expecting.
I want to create a simple menu in C program that accepts single character. The menu will be like this:
[S]how
[E]xit
If the user enter '1','s' or 'S' the program will print "Hello" and prompt again for the input
else if the user enters '2',E or 'E' the program ends.
else it should print "invalid input" and prompt again.
I am able to create the program but the problem is that when user enters 12, 13, 14, 15, 16.....so on starting with 1, it shows Hello and same for other options.
My code is:
#include <stdio.h>
void clearBuffer();
int main() {
int i = 0;
char selection;
do
{
printf("\t1. [S]how\n");
printf("\t2. [E]xit\n");
printf("Enter your selection from the number or character noted above: ");
scanf("%s", &selection);
clearBuffer();
if (selection == '1' || selection == 's' || selection == 'S')
printf("Hello");
else if (selection == '2' || selection == 'E' || selection == 'x')
i = 0;
} while(i != 0);
}
void clearBuffer()
{
while(getchar() != '\n');
}
If you are going to receive only one character consider replacing the scanf() function for getchar() function:
printf("Enter your selection from the number or character noted above: ");
selection = getchar();
You could use strlen, which is part of the standard C library, to check the length of the string returned by scanf and reject entries longer than one character:
if (strlen(selection) > 1)
{
printf("Invalid selection.");
}
Alternatively, I think you could use getchar() to accept just a single character from the user, which means they wouldn't have to press enter.
As already mentioned, you should use getchar() if you only want one character. If you still want to use scanf() for whatever reason you may have, the correct format is "%c", not "%s".
I would also suggest that if you are looking for a single character, the if block looks a little "busy" (read, awkward) ... a switch would be a cleaner, more elegant way to do it (IMHO).
/* something like this ... */
switch ( selection ) {
case '1':
case 's':
case 'S':
printf ( "Hello\n" );
break;
case '2':
case 'e':
case 'E':
i = 0;
break;
}
Other couple of things ... if you don't care about the case of the character being read (that is, 's' and 'S' will do the same thing), you can convert selection to uppercase before your if-block or switch-block using toupper(). Also, and this is just a style suggestion, don't use i for your exit flag. General practice is to use things like i and j for counters or indexes - you could use something like quit_now or user_done which would convey more precisely what the variable means.