Evaluating boolean with two char variables in c++ - c++

Apologies, a bit of a beginner here:
I'm working on a practice program to determine cost of a long distance call based on hour of the day and day of the week...and I've gotten to my do-while loop and am attempting to use nested branches to split up weekdays with the weekend.
However, when I compile and run, both the if and else if nested statements are skipped no matter if I put in the Chars corresponding to the booleans I'm attempting to evaluate. I'm struggling to understand what I'm missing here. The instructions clearly state that the days of the week should be stored in two char variables: Mo Tu We Th Fr Sa Su.
do
{
//have user input day of week of call
printf("\nOn what day was the call made? (Mo, Tu, We, Th, Fr, Sa, or Su) ");
scanf("%c%c", &day1, &day2);
//branch for weekday vs weekend vs invalid input
if (((day1 == 'M') && (day2 == 'o')) || ((day1 == 'T') && (day2 == 'u')) || ((day1 == 'W') && (day2 == 'e')) || ((day1 == 'T') && (day2 == 'h')) || ((day1 == 'F') && (day2 == 'r')))
{
//determine if phone call was made at hi or low rate times
printf("At what time was your call made? (HH MM - with 08 00 representing 8:00 AM and 18 30 representing 6:30 PM) ");
scanf("%f %f", &call_time_hour, &call_time_minute);
call_time_hour = call_time_hour + (call_time_minute / 60);
printf("%f", call_time_hour);
}
else if (((day1 == 'S') && (day2 == 'a')) || ((day1 == 'S') && (day2 == 'u')))
{
printf("What was the duration of your call? ");
scanf("%d", &call_duration);
//calculate total cost of call
cost_of_call = call_duration * 0.15;
printf("%s %.2lf", "The cost of this call was $", cost_of_call);
}
calls_made--;
printf("%d", calls_made);
}while (calls_made > 0);
So, for example, when I compile and run the program and enter "Sa" as the day that the call was made, it then moved directly to the 'calls_made--' step.

The problem is because previous scanf. Debug and look what characters are really scanned. I'm sure that day1 would be '\n'.
In this case clear the input stream before scanning the day of week:
while (getchar() != '\n');

Related

Pine Script - if / else if statement

I get the error : line 56: Mismatched input 'if' expecting 'end of line without line continuation'. on my code BUT when I delete some line of code under it the error disappear and the code compile.
Here the code with the error (line 56 is the 3rd line) :
SL = if long == 'long' and (close[1]-low[1])/low[1] > 0.012
Truncate(low[1], 2)
else if long == 'long' and (close[1]-low[1])/low[1] < 0.012
Truncate(low[1]-low[1]*0.017, 2)
else if long == 'long_renversement' and renversement_red_golong == 'yes'
Truncate(math.avg(low[1], close[1]), 2)
else if long == 'long_renversement' and renversement_green_golong == 'yes'
Truncate(math.avg(low[1], open[1]), 2)
else if long == 'long_continuation' and (close[1]-(math.avg(close[1], open[1]))/(math.avg(close[1], open[1]) > 0.012
Truncate(math.avg(close[1], open[1]), 2)
else if long == 'long_continuation' and (close[1]-(math.avg(close[1], open[1]))/(math.avg(close[1], open[1]) < 0.012
Truncate(open[1], 2)
else if short == 'short' and (high[1]-close[1])/close[1] > 0.012
Truncate(high[1], 2)
else if short == 'short' and (high[1]-close[1])/close[1] < 0.012
Truncate(high[1]+high[1]*0.017, 2)
else if short == 'short_renversement' and renversement_red_goshort == 'yes'
Truncate(math.avg(high[1], open[1]), 2)
else if short == 'short_renversement' and renversement_green_goshort == 'yes'
Truncate(math.avg(high[1], close[1]), 2)
else if short == 'short_continuation' and ((math.avg(close[1], open[1])-close[1])/close[1] > 0.012
Truncate(math.avg(close[1], open[1]), 2)
else if short == 'short_continuation' and ((math.avg(close[1], open[1])-close[1])/close[1] < 0.012
Truncate(open[1], 2)
And here the code when i delete the end of it (run without any error) :
SL = if long == 'long' and (close[1]-low[1])/low[1] > 0.012
Truncate(low[1], 2)
else if long == 'long' and (close[1]-low[1])/low[1] < 0.012
Truncate(low[1]-low[1]*0.017, 2)
else if long == 'long_renversement' and renversement_red_golong == 'yes'
Truncate(math.avg(low[1], close[1]), 2)
else if long == 'long_renversement' and renversement_green_golong == 'yes'
Truncate(math.avg(low[1], open[1]), 2)
If I delete less than that, the error stay there... I'm so confused...
The compiler error is not helpful, but the issue is that you have several misplaced brackets in your if/else block (which is counted as a single block, which is why the compiler sends you to the line where the block starts instead of the actual line with the issue):
// Five opening brackets, three closing brackets
else if long == 'long_continuation' and (close[1]-(math.avg(close[1], open[1]))/(math.avg(close[1], open[1]) > 0.012
<...>
else if long == 'long_continuation' and (close[1]-(math.avg(close[1], open[1]))/(math.avg(close[1], open[1]) < 0.012
// Three opening brackets, two closing brackets
else if short == 'short_continuation' and ((math.avg(close[1], open[1])-close[1])/close[1] > 0.012
<...>
else if short == 'short_continuation' and ((math.avg(close[1], open[1])-close[1])/close[1] < 0.012
Fix these and the code should compile properly.

Converting c++ switch with if statement to Sql

I wrote a bunch of code in c++ to check for a multiple conditions and also I make use of case. Now am struggling to convert it sql case. Below is the c++ code
Switch(TypeEmp){
case 0:
if(Age < 65){
if((income >=0) || (income <=1880000)){
amnt= income * 52 ;
}else if(other condition){
calculate it amnt;
}
}
break;
}
Somthing like this
select ...
case
when (Age < 65) then
case
when (Income >= 0) or (Income <= 1880000) then
income * 52
when (other condition) then
--TODO: compute other condition amount - "calculate it amnt"
else
--TODO: compute amount here
end
else
--TODO: return right value here
end as amnt
...
from MyTable(s)
It'd be something like
SELECT CASE
WHEN AGE < 65 THEN
CASE
WHEN INCOME >= 0 OR INCOME <= 1880000 THEN
INCOME * 52
ELSE
CALCULATE_IT_AMNT
END
ELSE
NULL
END AS SOME_VALUE
FROM SOME_TABLE
This presumes that SOME_TABLE contains the AGE and INCOME columns used in the calculation.

How to do input validation simply in C++?

I want to give an error message if the input is neither character c nor h but I can't get it to work! I looked up some other answers but they mostly use throw/catch method which I didn't understand at all. I just started programming and error handling is in Chapter 20 or 21. Help me out with the most simple way as possible.
This is what I've tried:
cout << "Enter 'c'(even) or 'h'(odd): ";
cin >> your_guess;
if((your_guess != ('c' || 'h')) == false) {
cout << "Wrong Input. Game is restarting... " << endl;
// restart the game ...
}
But it always says Wrong Input. ....
(your_guess != ('c' || 'h')) == false
is wrong. ('c' || 'h') simply evaluates to true. The built-in operator|| takes two bool arguments:
bool operator||(bool, bool)
And since 'c' and 'h' are both not NUL characters, they convert to true.true OR true is true. The language doesn't create some magical entity with which you can do operator==/operator!= with char to see if the character is among those you've listed.
Then, later the bool and char are promoted to int to do the inequality check. I'd guess your_guess won't be equal to 1. And I don't mean '1' (ASCII 49), but 1 (ASCII 1). So you've effectively written if(true)...
What you meant to say is:
(your_guess != 'c' || your_guess != 'h') == false
or
!(your_guess != 'c' || your_guess != 'h')
or
your_guess == 'c' && your_guess == 'h' // your_guess equal 'c' and 'h' at once?
and now you see that there's something wrong with the logic.
The right code for the condition is one of these:
your_guess != 'c' && your_guess != 'h'
!(your_guess == 'c' || your_guess == 'h')
It's just De Morgan's laws all around.
How to do input validation simply in C++?
If the above is not simple for you, you can use switch (because you're probably going to use it anyway). But each case tests variable against compile-time constant.
If the letters you want to check for are stored in a variable, I suggest this:
std::string valid_characters = "ch"; // this will be our "magical entity"
if(valid_characters.find(your_guess) == std::string::npos)
{
// you have entered a character that is not 'c' nor 'h'
}
You can try
switch(your_guess){
case 'c' :
case 'h' :
// do something
break;
default :
cout<<"invalid Input"<<endl;
break;
}
If you are doing an error message in c++, using cerr instead of cout might be something you may want to think about doing in addition to the changing:
your_guess!=('c'||'h'))==false
To one of the correct forms listed in the other answers

C++ problems. I need help to a very simple and basic problems in C++

I am new in programming and I need a little help at a problem in C++ .
The problem is :
I need to read 3 numbers and to determinate if this numbers can be a date or not . I need to say "YES" if the numbers can be a date or "NOT" if they can`t be a date.
I've tried this :
#include <iostream>
using namespace std;
int main(){
unsigned int z, l, a;
cin >> z >> l >> a;
if((z<32 && l==1) || (z==29 && l==2 && a%4==0) ||
(z<29 && l==2 && a%4>0) ||(z<32 && l==3) ||
(z<31 && l==4) || (z<32 && l==5) || (z<31 && l==6) ||
(z<32 && l==7) || (z<31 && l==8) || (z<32 && l==9) ||
(z<31 && l==10) || (z<31 && l==1) || (z<31 && l==12)) cout << "YES";
else cout << "NO";
return 0;
}
Question:
Could you help me find the missed cases?
Note:
My teacher commented that "It is almost done but you miss some cases". I tried to find this cases 2 hours but I didn't succeed ...
Quick answer:
The missed cases probably are due to the missed leap years as your code currently doesn't use correct checking for that. The right check for leap year is at the end of the answer.
Firstly, try and figure out what are the cases on a piece of paper:
date is consisted of positive numbers
start date of Gregorian calendar (add comment to inform the user for interval of valid dates)
Formulate the format, e.g. it could be: dd/mm/yyyy or mm/dd/yyyy, i.e. 1.03.2015
which months have 30, 31, 28, 29 (in which years) days
leap years and February
Regarding the code:
1.Use meaningful variables that have names that explain their purpose, i.e.:
replace unsigned int z, l, a; with variables like: int month, day, year;
2.Create separate if- else if statements for each of the above cases and add comments to indicate them (it will make your code easy to read and understand).
// check if January has 31 days
if(z<32 && l==1){
// check if February has 29 days and it isn't a leap year
} else if (z==29 && l==2 && a%4==0){
} //...
Bugs in your code:
1.Your current check for leap year: a % 4 == 0 is not entirely correct. A proper check for leap year looks something like:
if year modulo 400 is 0 then
is_leap_year
else if year modulo 100 is 0 then
not_leap_year
else if year modulo 4 is 0 then
is_leap_year
else
not_leap_year
and in code:
if(((year % 4) == 0) && (((year % 100)!=0) || ((year % 400) == 0)){
//leap year
}
2.The check for November is not right: (z < 31 && l == 1). It should be:
(z < 31 && l == 11)

Date Validation and Conversion in C++

I have to write 2 functions. One that takes in a date as a string and checks if its in mm/dd/yy format; if its not in the correct format, it should be edited to make it so. The other function should convert the validated date to the format "Month dd, 20yy".
I'm pretty sure I can take care of the second function, but I am having trouble with the first one. I just have no idea how to check if its in that format... any ideas?
I thought that this would work, but it doesn't seem to...
Updated code:
bool dateValidation(string shipDate)
{
string temp;
if(shipDate.length() == 8 )
{
if(shipDate[2] == '/' && shipDate[5] =='/')
{
int tempDay, tempMonth, tempYear;
//Gather month
temp = shipDate[0];
temp += shipDate[1];
//convert string to int
tempMonth = temp.atoi;
temp = "";
//Gather day
temp = shipDate[3];
temp += shipDate[4];
//convert string to int
tempDay = temp.atoi;
temp = "";
//Gather year
temp = shipDate[6];
temp += shipDate[7];
//convert string to int
tempYear = temp.atoi;
temp = "";
if(tempMonth > 0 && tempMonth <= 12)
{
if(tempMonth == 9 ||
tempMonth == 4 ||
tempMonth == 6 ||
tempMonth == 11 ||)
{
if(tempDay > 0 && tempDay <= 30)
{
if 30 days
}
}
else if(tempMonth == 2)
{
if(tempDay > 0 && tempDay <= 28)
{
if 28 days
}
}
else
{
if(tempDay > 0 && tempDay <= 31)
{
if 31 days
}
}
}
}
}
}
There are 4 things you want to check:
Is there 8 characters ? If not, then don't even bother checking anything else. It's not in the proper format.
Are the third and fifth characters '/'. If not, then you still don't have the proper format.
Check each pair for its valid values. A month has days between 1 and
31 at most, there are no more than 12 months and months range from 01
to 12. A year can be any combination of any 2 digits.
This should take care of the format, but if you want to make sure that the date is valid:
Check for valid number of days in each month (january 31, february
28-29...) and indeed check for those leap years.
This looks a lot like a project I am about to grade.... You should verify that it is Gregorian Calendar compliant if it is the project I am about to grade. 1/1/2012 is definitely valid though so what you may want to do and what I would hope you consider is creating a switch statement that examines for formats like 1/12/2012 and 10/2/2012 because these are valid. Then parse out the month day and year from these. Then verify that they are within the limit of the Gregorian calendar. If it is for a class which I would guess that it is, you should consider writing the verification as a separate function from the parsing function.
So first ask whether the date is too long if not, is it too short, if not which version is it, then pass the d m y to the verification function. This kind of modularity will simplify your code and reduce instructions.
something like
bool dateValidation(string shipDate)
{
string temp;
switch(shipDate.length())
{
case(10):
// do what your doing
verify(m,d,y);
break;
case(8):
//dealing with single digits
// verify 1 and 3 are '/' and the rest are numbers
verifiy(m,d,y);
break;
case(9):
//a little more heavy lifting here
// but its good thinking for a new programmer
verifiy(m,d,y);
break;
default:
//fail message
break;
}