Code fails to give expected result, stacking loops - c

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;
}

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');

Running C program returns -1.#QNAN0 instead of number stored in floating-point variable

Before going on, I'd like to say that this is my first time here and I don't know how things work yet so please pardon any errors on my part.
When compiled,(source code below) everything works fine except for the content of the float disp which is equal to -1.#QNAN0. Any help on this? Thanks in advance. Some parts of the code are not complete like the switch-case structure. Please temporarily that(Unless it affects the result).
The source code for the C program:
#include <stdio.h>
#include <stdlib.h>
float moneyup(float m);
int main()
{
char name[20];
char x;
int y;
float disp;
int hunger;
printf("\t\t**********************************************\n");
printf("\t\t* *\n");
printf("\t\t* How To Get Rich Quick! *\n");
printf("\t\t* *\n");
printf("\t\t**********************************************\n");
printf("\nThis is an experimental command line interface game made by NayNay AKA Nathan\n");
printf("\nPlease pardon the poor user interface.");
for(;;)
{
printf("\nPlease enter your name(one only)");
scanf("%s", &name);
printf("\nThe name you entered is %s. Is this correct? (type y/n for yes or no)\n");
fflush(stdin);
x=getchar();
if(x=='y') /*This part with the for loop is used to get the name of the*/
{ /*user and confirm the correctness of that name. If the name is*/
printf("Okay! Moving on..."); /*wrong, the user has the option to change it. Bulletproofing used*/
break; /*here*/
}
else if(x=='n')
{
printf("Alright let's try again.");
continue;
}
else
{
printf("Let's try this again.");
continue;
}
}
printf("\nOkay %s, Let's get this story started",name);
printf("\n\nOne sad dreary morning, %s got up from sleep and went to the kitchen to get breakfast.");
printf("\nUnfortunately for him his pantry only contained a bunch of cockroaches going at it and laying their eggs everywhere");
printf("\nHe then checked his pockets and pulled out his last 5-dollar bill. That was all he had left,");
printf("\nHe bought a sandwich for $2 and decides to start a business with $3 as capital");
printf("\n\nChoose how to start");
printf("\n1. Begging.");
printf("\n2. Mow lawns.");
printf("\n3. Apply for post of newspaper boy.");
fflush(stdin);
y=getchar();
switch(y)
{
case '1':
printf("You begged for 6 hours and got $5.25\n");
disp=moneyup(5.25);
printf("You now have $%f\n",disp);
}
return 0;
}
float moneyup(float m)
{
float money;
money=(float)money+m;
return(money);
}
The variable money is uninitialized in the function moneyup when used in expression
money=(float)money+m;

C: Scanf in while loop executes only once

I am trying something simple in C, a program to get the exchange and do some conversions.
To make sure scanf gets the right type I placed it into a while loop, which continues to ask for input until a number is inserted.
If I enter a character instead of a number it does not ask again for an input.
exRate = 0;
scanfRes = 0;
while(exRate <= 0){
printf("Enter the exchange rate:");
while(scanfRes != 1){
scanfRes = scanf(" %f", &exRate);
}
if(scanfRes == 1 && exRate > 0){
break;
}
printf("Exchange rate must be positive.\n");
}
UPDATE: As this is a course assignment, I was not supposed to use anything outside of the taught material. When I asked the academic staff about handling unexpected input, I got an answer that this is a scenario I am not supposed to take into consideration.
The answers and help in the comments is all useful and I added 1 to all useful suggestions. The staff answer makes this question no longer needed.
Change handling of scanf() result.
If the input is not as expected, either the offending input data needs to be read or EOF should be handled.
for (;;) {
printf("Enter the exchange rate:");
scanfRes = scanf("%f", &exRate);
if (scanfRes == 0) {
printf("Exchange rate must be numeric.\n");
// somehow deal with non-numeric input, here just 1 char read & tossed
// or maybe read until end-of-line
fgetc(stdin);
} else if (scanfRes == EOF) {
// Handle EOF somehow
return;
} exRate > 0){
break;
}
printf("Exchange rate must be positive.\n");
}
Note: the " " in " %f" is not needed. "%f" will consume leading white-space.

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...

Switch and default: for 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)

Resources