switch case loop statement - if-statement

I am having a problem with my one assignment. I made one function name chequingsaving and when I call this function, it prints some data which is correct, but when I entered character depends on my selection of account it directly goes out of the loop. If I entered a correct character value, then same thing happens. That function code is below. Help me to find out my mistake. The thing is I also used a switch case, but still it directly goes to default. Same thing happens with if/else loop.
void chequingsaving() /*Chequing and saving account function*/
{
char a;
double r, Initialamount = 0;
printf(" c) Chequing\n");
printf(" s) Savings\n");
printf("Which account would you like to use?\n");
scanf("% c", &a);
if (a == 'c' || a == 'C')
{
printf("Please enter the amount for deposit\n");
scanf("% lf", &r);
Initialamount = Initialamount + r;
printf("Your chequing account balance is=%lf", Initialamount);
}
else
if (a == 's' || a == 'S')
{
printf("Please enter the amount for deposit\n");
scanf("%lf", &r);
Initialamount = Initialamount + r;
printf("Your chequing account balance is=%lf", Initialamount);
}
else
printf("Invalid character\n");
}

Remove the space in scanf:
scanf("%c", &a);
and also in the following scanf:
scanf("%lf", &r);

Your scanf is not correct, you have space "% c".

Related

A "misplaced else" error in this C++ program

I cannot seem to fix the "misplaced else" error in the code below. This code should collect and compute for term grades and give remarks depending on the score.
#include <conio.h>
#include <stdio.h>
main()
{
char name[20];
int exam, q1, q2, q3, ass, sw, att, avgq, CS, TG;
clrscr();
printf("Name: ");
gets(name);
printf("\nExam: ");
scanf("%d", &exam);
printf("\nQuiz #1: ");
scanf("%d", &q1);
printf("\nQuiz #2: );
scanf("%d", &q2);
printf("\nQuiz #3: ");
scanf("%d", &q3);
printf("\nAssignment: ");
scanf("%d", &ass);
printf("\nSeatwotk: ");
scanf("%d", &sw);
printf("\nAttendance: ");
scanf("%d", &att);
CS = (0.4*ass) + (0.4*sw) + (0.2*att); // class standing //
avgq = (q1 + q2 + q3)/3; // Average quiz //
TG = (0.4*exam) + (0.3*avgq) + (0.3*CS); // Term grade //
if(TG >= 90)
printf("Term Grade: %d", TG);
printf("Remarks: EXCELLENT");
else if (TG>=80 && TG<=89)
printf("Term Grade: %d", TG);
printf("Remarks: SATISFACTORY");
else if (TG>=76 && TG<=79)
printf("Term Grade: %d", TG);
printf("Remarks: GOOD");
else if (TG == 75)
printf("Term Grade: %d", TG);
printf("Remarks: PASSING");
else if (TG<74)
printf("Term Grade: %d", TG);
printf("Remarks: FAILED");
else
printf("Invalid Input. Try again");
getch();
return 0;
}
Uh oh! Noob alert! Just kidding; we all have to start somewhere ;)
So do not worry, fair maiden! The problem lies here:
When you declare an if statement, you must encompass the body of the if statement with curly braces. If you don't do that, only the first line below the if statement will be run. Here's an example:
// Here, both do something 1 and do something 2 are being run in the 'if' statement
if (something) {
do something 1;
do something 2;
}
// Here, only do something 1 will get run inside the 'if' statement
if (something)
do something 1;
do something 2;
So back to your problem. You must put curly braces {} around the code in an if statement if the if statement body consists of more than one line.
if (something)
do something 1;
do something 2;
else
do something 3;
is equivalent to
if (something)
do something 1;
do something 2;
else do something 3;
That is why your else statement throws an error. Each else must have an if before it.
C++ doesn't use indentation to determine the ends of statements. You need braces if you want more than one statement.
Instead of:
if (a)
b;
c;
else
d;
Use:
if (a) {
b;
c;
} else {
d;
}
If you have more than 1 line under an if or else, they must be contained in curly braces, like this:
if(TG>=90)
{
printf("Term Grade: %d",TG);
printf("Remarks: EXCELLENT");
}
else if (TG>=80 && TG<=89)
{
printf("Term Grade: %d",TG);
printf("Remarks: SATISFACTORY");
}

Logic operators in if statments

So i am writing a calculator as an exercise in c++, were you first select operators +, -, * or / by inputting a, s, m or d. The calculator works fine, except for a filter i set up to respond with an error if the user inputs something other than a, s, m or d. The filter is an if statement:
if(Opperator=='a'||'s'||'m'||'d')
{
//some code
}
else
{
//"Operatorfault"
cout <<"opperatorfeil";
}
Even though the "operator" has other char values than those the if statement is suppose to execute, the code within the if statement is still executed. The whole code is below. The outputs and variables are in Norwegian, but i have tried to translate in the comments.
#include <iostream>
using namespace std;
//The calculator function
int Kalkulator(int IN1, int IN2, char Opperator)
{
int Svar;
//Detects witch operator the user choose, and preforms the assigned operation
if(Opperator=='a')
{
Svar=IN1+IN2;
}
if(Opperator=='s')
{
Svar=IN1-IN2;
}
if(Opperator=='m')
{
Svar=IN1*IN2;
}
if(Opperator=='d')
{
Svar=IN1/IN2;
}
//Returns the answer
return Svar;
}
int main()
{
//Input a, s, m or d for addition, subtraction, multiplication or division, respectively
cout <<"Skriv \"a\" for addisjon, \"s\" for subtraksjon, \"m\" for multipliksjon, og \"d\" for divisjon";
cout <<endl;
cout <<endl;
char Opperator;
cin >>Opperator;
cout <<endl;
//Checks if the input is valid
if(Opperator=='a'||'s'||'m'||'d')
{
cout <<"Skriv inn det første tallet du vil gjøre opperasjonen på, trykk derreter enter, og skriv inn det andre";
cout <<endl;
cout <<endl;
int IN1;
int IN2;
cin >>IN1;
cin >>IN2;
cout <<endl;
//"The answer is"
cout << "Svaret er: ";
//Calls the calculator function, and inputs the values it has gathered, then prints the answer
cout <<Kalkulator(IN1, IN2, Opperator);
}
else
{
//"Operatorfault"
cout <<"opperatorfeil";
}
return 0;
}
The error is in your if statement. In C++, when you are comparing the same variable to multiple values, for example if opperator is a, m, s, d, you need to restate the variable for each comparison.
if( Opperator=='a' || Opperator=='s' || Opperator=='m' || Opperator=='d' )
Instead of your current if statement.
Also, as a tip, a switch statement is much better in these cases, you can simply state
int ans;
switch (customerPackage) {
case 'a':
ans = int1 + int2;
case 's':
ans = int1 - int2;
case 'd':
ans = int1 * int2;
case 'm':
ans = int1 / int2;
default:
string ans;
ans = "invalid input";
}
cout <<ans;
This is wrong:
if(Opperator=='a'||'s'||'m'||'d')
you can NOT test for equality (or inequality) like this. The code executes as the equivalent of
if (Operator == (result of boolean ORs))
You have to test for equality individually:
if ((op == 'a') || (op == 's') || etc...)
Why not just break it out like so,
if (Opperator == 'a' ||
Opperator == 's' ||
Opperator == 'm' ||
Opperator == 'd')
{
// Good values
}
else
{
// Bad values
}
if(Opperator=='a'||'s'||'m'||'d')
It checks whether Opperator is equal to 'a', if not then 's' always returns true and so all logic becomes true.
You can use if statement:
if (Opperator == 'a' || Opperator == 's' || Opperator == 'm' || Opperator == 'd') {
// my calc works well
} else {
// again my calc works well
}
OR you can use switch:
switch(Opperator) {
case 'a':
case 's':
case 'm':
case 'd': // do normal operation here
break;
default: // error handle
break;
}
You must test each char for equality:
if(Opperator=='a'||Opperator=='s'||Opperator=='m'||Opperator=='d') {
...execute
} else {
...execute something else
}
If you want to be fancy you can use algorithm::anyOf().
#include <algorithm>
const std::vector<char> validValues{'a','s','m','d'};
if(any_of(validValues.begin(),
validValues.end(),
[&](const char &x) { return x == Opperator; }) {
// good values
} else {
// bad values
}

array boundary checking and input validation

I am writing the hangman game in C++ and I was wondering how I can make sure that the word that my first user inputs just contains alphabetic characters, nothing else. I have to prompt the user to enter a new word when the word that they have already entered is not valid.
there are functions I use to do that but for some my check boundary function does not work properly. Please help, I have no idea how to fix it. In my first function I ask the user's input but and then I use another function to error check this word.
word1 is the array that has stored my first word, and I assume that the letters are all in lower case for now . so I use the ASCII value of the characters to make sure that it is within the boundary. but say if I enter 45 it does ask me to reenter the word but the second word will be accepted no matter what it is . it could be |*%^% it accepts it anyway.
void CheckBound (char word1[], int SIZE1)
{
int i;
int w1[SIZE4];
int found;
for (i=0;i<strlen(word1);i++)
{
w1[i]=(int)word1[i];
if (w1[i] >= 97 && w1[i] <= 122)
found=1;
else
{
printf("Please re-enter your word: ");
fgets(word1, SIZE1, stdin);
word1[strlen(word1)-1]='\0';
printf("%s \n", word1);
}
}
return;
}
When you detect a non-alphanumeric character, you are still in the first loop iterating over each character of word1. Once the user has entered a new word, the loop continue with i!=0, which is of course incorrect.
Try this instead:
oid CheckBound (char word1[], int SIZE1)
{
int i;
bool ok = false;
while(!ok)
{
ok = true;
for (i=0;i<strlen(word1);i++)
{
int c = word1[i];
if (c < 97 || c > 122)
{
ok = false;
break;
}
}
if(!ok)
{
printf("Please re-enter your word: ");
fgets(word1, SIZE1, stdin);
word1[strlen(word1)-1]='\0';
printf("%s \n", word1);
}
}
}
By the way, this is C, not C++.
typical C++ would use:
std::string instead of char array/char pointers for storing strings
std::vector, std::array for arrays (instead of plain C arrays)
streams for printing and inputting text

How to handle this exception

I am writing this code to allow user to play game "Guess the number". Once the user guesses right number it asks user if he/she wants to play again. This code works for two plays and if user inputs 'y' to play again for third time, the code shows exception. The exception details are:"Unhandled exception at 0xFEFEFEFE in Ex 5.32 Guess the number.exe: 0xC00001A5: An invalid exception handler routine has been detected (parameters: 0x00000003)."
#include "stdafx.h"
#include <math.h>
#include <stdlib.h>
int a = 1;
int main(int g){
int num, guess;
char YesOrNo;
srand(g);
num = 1 + rand() % 1000;
printf("I have a number between 1 and 1000\nCan you gess my number?\n");
do{
scanf_s("%d", &guess);
if (guess == num){
printf("Excellent! You guessed the number!\n");
break;
}
else if (guess < num)
printf("Too low. Try Again.\n");
else
printf("Too High. Try Again.\n");
} while (1);
printf("Would you like to play again(y or n) ? ");
scanf_s("%s", &YesOrNo);
if (YesOrNo == 'Y' || 'y'){
a++;
main(a);
}
else{
return 0;}
}
Have your scanf_s use the correct format specificer:
scanf_s(" %c", &YesOrNo, 1); // expecting a char
instead of:
scanf_s("%s", &YesOrNo); // expecting a string
If you were using the standard scanf() using the wrong format string can lead to undefined behavior… not positive about the same for scanf_s() but it can’t be good.
Also note that scanf_s() requires a size to be passed with character or string input (hence the 1 after the YesOrNo parameter):
Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.
Also... you tagged this with both C and C++, note that C allows you to call main() from within itself while C++ does not. Although, frankly IMO there's never a good reason to do this, and I don't see a good reason for your program to.

Why is the else statement still printing after the if statement is satisfied?

Sorry I'm new to stackoverflow but I had a problem while coding. I created this simple
program but I noticesd that it still printed the else statement after it was done with the if statement. The code is written in c++ and your help is deeply appreciated.
# include <iostream>
using namespace std;
int main()
{
char check;
bool done = false;
while(not done)
{
cout<<"Please enter one of the options provided below."<<endl;
cout<<"D = distance S = second F = first"<<endl;
cin>>check;
if(check == 'D')
{
cout<<"You pressed D"<<endl;
}
if(check == 'S')
{
cout<<"You pressed S"<<endl;
}
if(check == 'F')
{
cout<<"You pressed F"<<endl;
}
else
cout<<"You suck!";
}
return 0;
}
For example, when I press D, I only want to receive You pressed Das the output. Instead I get You pressed D You suck!
I'm pretty sure you wanted else if (i.e. nested) instead of (subsequent) ifs, but that's just a guess since you provide no input or output.
Not too often that I think just posting the exact code is the best way to educate but in this case I think the difference will jump out at you:
if(check == 'D')
{
cout<<"You pressed D"<<endl;
}
else if(check == 'S')
{
cout<<"You pressed S"<<endl;
}
else if(check == 'F')
{
cout<<"You pressed F"<<endl;
}
else
cout<<"You suck!";
Make sure you understand the difference between if, else if, and else.
Also this is a standard situation in which to use a switch statement instead.