Switch and default: for C - c

Sorry if this sounds like a very basic question, it is my first time on here!
I am having some difficulties with coding for C, specifically with a switch and the default of that switch. Here is some example code:
#include<stdio.h>
int key;
main()
{
while((key=getchar())!=EOF)
{
printf("you pressed %c \n",key);
switch(key){
case'0':
case'1':
case'2':
case'3':
printf("it's a numeral\n");
break;
default:
printf("it's not a numeral\n");
}
}
}
The actual code is a bunch longer, this is purely an example.
So the code compiles it and I execute it, but I get:
"You pressed 1, it's a numeral, you pressed , it's not a numeral."
My code seems to 'fall through' and repeat itself without referring to either one. If anyone could help that would be great as this is an example in a text book and I am utterly stuck!
Kindest Regards.

You need to account for entering the Enter key, which produces a '\n' on *nix systems. I am not sure what pressing the Enter key does on Windows systems.
Here's your original code doctored up to eat the return key.
#include<stdio.h>
int key = 0;
main()
{
while((key=getchar())!=EOF)
{
if('\n' == key)
{
/* Be silent on linefeeds */
continue;
}
printf("you pressed %c \n",key);
switch(key){
case'0':
case'1':
case'2':
case'3':
printf("it's a numeral\n");
break;
default:
printf("it's not a numeral\n");
}
}
}
You maybe using getchar() for a specific reason, but my experiences in C usually involved reading the whole line, and RTL functions like scanf will eat the line terminator for you.

You need to eat the newline character, that is put in the read buffer when you hit return.
Issue another call to getchar after or before the switch to solve your problem.

Here is an idea...immediately before the printf(), insert logic to ignore spaces and all control characters...
if(key <= ' ')
continue;
printf(...) ...

I dont know if that is the problem, but you have three case without a break. So you press key "1" and there is nothing to do for the programm and so ins go to the next case how is right and this is the default.
Although you take a char in an int-variable???
In your Example it is a better way to take a if-clause like this:
#include<stdio.h>
char key;
main()
{
while((key=getchar())!=EOF)
{
printf("you pressed %c \n",key);
if(key == '0' || key == '1' || key == '2' || key == '3'){
printf("it's a numeral\n");
}
else {
printf("it's not a numeral\n");
}
}
Code is not tested. ;-)
The best way in bigger programms is to work with regular expressions.
I hope, this answer was helpful.

the problem might be due to, input buffer not flushing. when "1" is matched in the switch case, a newline character remains in the buffer.
try this,
fflush(stdin)

Related

Nested if statement in C - why doesn't it evaluate the last else if?

The following code does not execute the last else if statement when you assign to choice value 3.
#include<stdio.h>
#include<stdlib.h>
int main() {
puts("Specify with a number what is that you want to do.");
puts("1. Restore wallet from seed.");
puts("2. Generate a view only wallet.");
puts("3. Get guidance on the usage from within monero-wallet-cli.");
unsigned char choice;
choice = getchar();
if ( choice == '1' ) {
system("nice -19 ~/monero-x86_64-linux-gnu-v0.17.2.0/monero-wallet-cli --testnet --restore-deterministic-wallet");
exit(0);
}
else if ( choice == '2' ) {
system("nice -19 ~/monero-x86_64-linux-gnu-v0.17.2.0/monero-wallet-cli --testnet --generate-from-view-key wallet-view-only");
exit(0);
}
else if ( choice == '3' ) {
puts("Specify with a number what is that you want to do.");
puts("1. Get guidance in my addresses and UTXOs");
puts("2. Pay");
puts("3. Get guidance on mining.");
unsigned char choicetwo = getchar();
if ( choicetwo == '1' ) {
printf("Use \033address all\033 to get all your addresses that have any balance, or that you have generated at this session.");
printf("Use \033balance\033 to get your balance");
printf("Use \033show_transfers\033 to get ");
printf("Use \033show_transfers\033 out to get ");
printf("Use \033show_transfers in\033 to get your balance");
}
}
return 0;
}
I get the following output When I enter 3:
Specify with a number what is that you want to do.
1. Restore wallet from seed.
2. Generate a view only wallet.
3. Get guidance on the usage from within monero-wallet-cli.
3
Specify with a number what is that you want to do.
1. Get guidance in my addresses and UTXOs
2. Pay
3. Get guidance on mining.
I'm really blocked, something is missing and I have no clue why it does not proceed to take the input from the user for the second time.
When you enter "3" for the first input, you're actually inputting two characters: the character '3' and a newline. The first getchar function reads "3" from the input stream, and the second one reads the newline.
After accepting the first input, you'll want to call getchar in a loop until you read a newline to clear the input buffer.
choice = getchar();
while (getchar() != '\n');

Code fails to give expected result, stacking loops

I'm a student and I'm currently learning C without much experience on programming, I've been trying to create a program that receives a "password" from the user and then proceeds to check if the password has at least one letter,number and special character. I wrote some code but it doesn't give the expected results while I struggle to find what's wrong with it.
If I input a "just numbers" password or "just special characters" it does fine by returning "You missed a letter"
If I input a "just characters" password it doesn't return anything, same for a normal password that contains all 3
That's the code:
int main()
{
char a[20];
int b = 0 ,c = 0,d=0;
printf("Please type your password and make sure it contains a letter a number and a special character:");
scanf("%s",a);
while(b<=20){
if(isalpha(a[b])){
break;
while(c<=20){
if(isdigit(a[c])){
break;
while(d<=20){
if(isalpha(a[d]) || isdigit(a[d])){
d++; continue;
}else{
printf("Congratulations your Password has been saved\n");
}
} printf("You missed a special character\n");
}else{c++; continue;}
}
printf("You missed a number\n");
}else{b++; continue;}
}
(b>20) ? printf("You missed a letter\n") : printf("");
return 0;
}

Why both of if statements are executed no matter what the input is?

In my choose your own adventure, A and B are both inputs that result opening input functions. Whichever is put down, they are both displayed.
#include <stdio.h>
int main()
{
char firstname[15];
char class;
char swordch0c1;
char enter;
printf("Hello there! Could I have your first name?\n");
scanf("%s",firstname);
printf("\n---------------------The Legend of %s---------------------",firstname);
printf("\nPress Enter to continue.");
enter=getch();
if(enter=='\n');
printf("\n\n\nYou are %s, a: \nA.Swordsman\nB.Assassin\nC.Archer\nD.Mage\n",firstname);
scanf("%c", &class);
/*swordsman story starts here*/
if(class=="A");
{
printf("\n\nThere you stand, at your boring everyday post.\nWhen you joined the army, you thought it would be more exciting than this.\nJust then, you see your general walking towards you.");
printf("\n\nYou quickly improve your posture. \"Soldier, I have an opurtunity for you\"\nA.\"Really? What is it?\"\nB.\"I'm not interested\"\n");
scanf("%d",swordch0c1);
if(swordch0c1=="b");
{
printf("\"But... I didn't even tell you what it was. Okay, suit yourself\" You are DOOMED to a life of boredom.\n\n\n\n\n");
}
if(swordch0c1=="a");
{
printf("\n\n\n\"Well, you see, there's this dragon. He's been causing big problems. \nHe's destroyed villages, harrassed the priests on the mountain,\n");
printf("and even attacked a couple cities. His name is Sorrith, and dozens of knights have already tried to kill him, none of them being successful.\"");
printf("\nA.\"Say no more, I'll do it.\"\nB.\"Dragon? No way! You better find someone else.\nC.\"Keep talking...\"");
}
}
return 0;
}
I apologize if I'm not specific/clear enough.
I'm using Windows BTW.
You made a few mistake, but this should work!
#include <stdio.h>
int main() {
char firstname[15], character, swordch0c1, enter;
printf("Hello there! Could I have your first name?\n>");
scanf("%s", &firstname);
printf("\n---------------------The Legend of %s---------------------", firstname);
printf("\nPress Enter to continue.");
enter=getch();
printf("\n\n\nYou are %s, a: \nA.Swordsman\nB.Assassin\nC.Archer\nD.Mage\n>", firstname);
scanf(" %c", &character);
/*swordsman story starts here*/
if (character == 'A') {
printf("\n\nThere you stand, at your boring everyday post.\nWhen you joined the army, you thought it would be more exciting than this.\nJust then, you see your general walking towards you.");
printf("\n\nYou quickly improve your posture. \"Soldier, I have an opurtunity for you\"\nA.\"Really? What is it?\"\nB.\"I'm not interested\"\n>");
scanf(" %c", &swordch0c1);
if (swordch0c1 == 'b')
printf("\"But... I didn't even tell you what it was. Okay, suit yourself\" You are DOOMED to a life of boredom.\n\n\n\n\n");
if (swordch0c1 == 'a') {
printf("\n\n\n\"Well, you see, there's this dragon. He's been causing big problems. \nHe's destroyed villages, harrassed the priests on the mountain,\n");
printf("and even attacked a couple cities. His name is Sorrith, and dozens of knights have already tried to kill him, none of them being successful.\"");
printf("\nA.\"Say no more, I'll do it.\"\nB.\"Dragon? No way! You better find someone else.\nC.\"Keep talking...\"");
}
}
return 0;
}
Remove all the semicolons after each if and also use ' instead of " in all the if(...) . Also,
scanf("%d",swordch0c1);
Is wrong as swordch0c1 is not an int. Use %c instead of %d as it is a char that you are scanning
You put semicolons after your both if...
Change if(swordch0c1=="b"); by if(swordch0c1=='b') and if(swordch0c1=="a"); by if(swordch0c1=='a')
I think you should read again your C tutorial or your C book, chapter instruction.
Don't put semicolon after if statement, otherwise it would skipped. Always use single quote for a char, and double for string.

Parameters inside the function

I have a work to do in which I have to keep a loop inside the function expecting the following parameters:
-"i" to insert
-"s" to search
-"q" to quit
How do I keep this loop? I've looked up some options and it seems to be possible using a while or a switch, but I am not sure which is the best way to read those chars (with a fscanf perhaps?). I am also not sure how to read the things after the parameter "i" as the input would be "i word 9", so after detecting the i to insert I have to read a string and an int.
Anyone has any idea how to do this? I am sorry is this seems simple, but I am new to programming.
edit: Here is what I have so far
while (loop) {
fscanf(stdin,"%c",&par);
if (strcmp(&par,"i")){
scanf("%s %d",palavra,p);
raiz = insere(raiz,&palavra,p);
}
else if (strcmp(&par,"b")){
scanf("%s",palavra);
busca(raiz,&palavra);
}
else if (strcmp(&par,"q"))
loop = 0;
}
edit 2: This is what I have now, I am having problems reading the string and integer when the parameter is i, somehow it crashes the function
while (1) {
c = getchar();
if (c == 'f')
break;
else if (c == 'i'){
fscanf(stdin,"%s",&palavra);
scanf("%d",&p);
raiz = insere(raiz,palavra,p);
}
else if (c == 'b') {
scanf("%s",palavra);
busca(raiz,palavra);
}
}
Thanks in advance!
The code you have doesn't look too bad compared to what I believe you want. You can replace the "while (loop)" with "while (1)" and then your exist code "loop = 0;" with "break;" which is a bit more standard way of doing things. Also "fscanf(stdin..." is the same as "scanf(..." ... scanf will read from stdin by default. You might want to check the docs for strcmp because it returns 0 for an exact match and I don't think that will do what you want in your 'if' statements. You should be able to use scanf to read in the values you want, is it giving you an error?
You are using 3 separated scans. That means you can't input this "i word 9", but input one command or parameter at the time separated by EOL(pressing enter).. i, enter, word, enter, 9, enter ... Then the function should actually get further in those "if"s. With those scans you also should consider printing information about expected inputs ("Choose action q/i/f")
And I would recommend using something to test those inputs.
if (scanf("%d", &p) == 0) {
printf("Wrong input");
break;
}

program running through my if else after function call

I have a class assignment in C to make a simple calculator that performs three calculations. I haven't completed all of the functions yet but I am having a problem with my calcMenu function. When the function is called the program runs through all of the if else statements and unknown to me, performs only the else statement which is error checking. Than the function is run again which is intended but this time it does not run through all of the if else statements and allows the user to make a choice. I know I have done something really stupid but have been racking my brain for the last hour. If anyone has any pitty for me, than please point me in the right direction. I know all the system calls will Irk some but this is a basic class and our instructor has told us to use them.
Thanks in advance,
Mike
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define pause system ("pause")
#define cls system ("cls")
//Prototype calculate functions here
void evenOrOdd(int userNumber);
void squareNum(int userNumber);
void cubeNum(int userNumber);
void calcMenu(int userNumber);
void main() {
//Declare local variables here
int userNumber = 0;
printf("\t\t\tThe amazing three function caluculator\n\n\n");
printf("Please enter a whole number that you would like to calculate\n");
scanf("%d", &userNumber);
calcMenu(userNumber);
}
void calcMenu(int userNumber)
{
char calculateOption;
printf("\nWhat calculation would you like to perform with your number?\n\n");
printf("Press A.) to check if your number is even or odd.\n\n");
printf("Press B.) to calculate the square of your number.\n\n");
printf("Press C.) to calculate the cube of your number.\n\n");
printf("press D.) to exit the program.\n");
scanf("%c", &calculateOption);
calculateOption = toupper (calculateOption);
if (calculateOption == 'A')
{
evenOrOdd(userNumber);
}
else if (calculateOption == 'B')
{
squareNum(userNumber);
}
else if (calculateOption == 'C')
{
cubeNum(userNumber);
}
else if (calculateOption == 'D')
{
system("cls");
printf("Thank You for using my amazing calculator.\n\n");
system ("pause");
system ("exit");
}
else
{
printf("Please enter a valid choice");
calcMenu(userNumber);
}
}
void evenOrOdd(int userNumber) {
userNumber = userNumber %2;
if (userNumber == 0)
{
printf("Your number is even. \n");
}
else
{
printf("Your number is odd. \n");
}
}
void squareNum(int userNumber) {
}
void cubeNum(int userNumber){
}
When you read input with scanf you have to press the Enter key to make the program continue. Your scanf call reads the single character from the input, but leaves the Enter key still in the input buffer, to be read next time you call scanf.
There is a very simple trick to solve that: Place a space in the scanf format string before or after the "%c". This will make scanf skip whitespace.
scanf("%c ", &calculateOption);
If you stepped through the code with a debugger you would have easily seen that calculateOption would have been the newline character.
First of all, You can condense all those printf statements into one function to save the extra calls.
Next, you should probably indent your functions, I can't tell where one begins and another ends at a glance.
Third, don't use system("pause"), use getchar().
Fourth, this is optional, you might want to turn those if statements into a switch statement.
Now, on to your question. First of all, instead of using scanf("%c", &calculateOption), just use getchar() here too. In this case, I would write calcMenu() as this:
int calcMenu(int userNumber){
printf("\nWhat calculation would you like to perform with your number?\n\n\
Press A.) to check if your number is even or odd.\n\n\
Press B.) to calculate the square of your number.\n\n\
Press C.) to calculate the cube of your number.\n\n\
Press D.) to exit the program.\n");
switch(toupper(getchar())){
case 'A':
evenOrOdd(userNumber);
break;
case 'B':
squareNum(userNumber);
break;
case 'C':
cubeNum(userNumber);
break;
case 'D':
system("cls"); //this is bad, really.
printf("Thank You for using my amazing calculator.\n\n");
getchar();
return 0;
default:
printf("Please enter a valid choice: ");
calcMenu(userNumber);
break;
}
}
Also, main should always return a value. void main is bad practice.
Disclaimer: The code isn't tested, you shouldn't copy/paste it anyways. I also don't know if you're being forced to use some things or not...

Resources