Using characters in a conditional statement in C++ - c++

I am trying to write a program which asks for tuition credits and for undergraduate or graduate classes. User enters the number of credits, then must enter U for undergraduate or G for graduate. I am having issues with the conditional statement, if the user enters U, then the price of the undergraduate credits will compute and output, similar with graduate. I am trying to enter U at the IF condition, but either one price or the other outputs.
#include <stdlib.h>
#include <iostream.h>
int main ()
{
const double Under = 380.00 ;
const double Grad = 395.00 ;
char U , G ;
double First, Second, Third, Fourth, Fifth, Sixth ;
cout << endl << endl ;
cout << " To calculate your tuition enter the amount of credits, then enter type of" ;
cout << endl ;
cout << " classes." ;
cout << endl << endl ;
cout << " Enter number of credits. " ;
cin >> First ;
cout << endl << endl ;
cout << " Enter U for Undergraduate or G for Graduate: " ;
cin >> Second ;
cout << endl << endl ;
cout << " Your tuition total is: " ;
Third = First * Under ;
Fourth = First * Grad ;
if ( Second == U )
cout << Third ;
else
cout << Fourth ;
cout << endl << endl ;
system ("Pause");
}

Ok I see a few problems here.
The main one is that characters in C++ have single quotes, like this 'c'. This is most likely the cause of your error. Since you never initialized U anywhere, either do initialize it to 'U' or try
if ( Second == 'U' )
cout << Third ;
Second, though this is not necessarily an error typing cout<<endl<<endl; is a little wasteful as it flushes the buffer for cout twice with only 1 character added in between. typing cout<<'\n'<<endl; would fix that.

You never give a value to U. Right now its content is garbage which is why you get random behavior. Try either assigning 'U' to your variable U or changing the confiditional to:
if( Second == 'U' )

It is more or less all of the already stated:
Remove the declaration of char U since it is never used
Change the type of Second to char (remove from the double list and add char
Second;)
Change the if statement to if ( ( Second == 'U' ) || (
Second == 'u' ) )

I don't see U = 'U' anywhere. You is declared at beginning, but never initialized. You U is just a variable. You have to assign the character 'U' in it.

Second is declared as a double, but it looks like you are expecting the user to enter a character.

use
using namespace std;
under header file

Related

enter Odd, Even, zero and negative numbers and count using for and while loop in C++ without using arrray

I've met some problem during programming. I want to write a program to differentiate even numbers, odd numbers, zero values and negative numbers by using while and for loop.
1st question :
However, when I try to run my program, the last number I've entered will not be counted. I know it occur because of my o++ put at the top of the if condition, how should I solve my problem?
2nd question :
For the for loop parts, actually it may ignored those negative values. How should I solve it to let the negative numbers also count in loop ? May I changed the num>0 to num < 100000 to let the for loop works?
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
int main ()
{
int num ,numbers = 1 ;
char answer = 'Y' ;
int o=0, e=0, z=0 ,n=0 ;
// o for odd numbers, e for even numbers, z for zero values, n for negative numbers
cout << "Enter number" << numbers << ": " << endl ;
cin >> num ;
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
{
if (num % 2 == 0 && num > 0)
{
e++ ;
cout<< "The number of even numbers is :" << e << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num ;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num % 2 == 1 && num > 0)
{
o++;
cout<< "The number of odd numbers is :" << o << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num == 0)
{
z ++;
cout<< "The total of 0 is :" << z << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
}
cout << "The total even numbers is :" << e << endl;
cout << "The total odd numbers is :" << o << endl ;
cout << "The total negative numbers is :" << n << endl ;
cout << "The total zero number is:" << z << endl;
return 0;
}
This line, in main() is really puzzling:
// ...
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
The for(;;) statement is your main loop. The while statement will be executed as long as num is positive.
Let's look at this for() statement in detail:
for (num = num; // num = num ??? this statement does nothing.
num > 0; // the while statement (and the contents of the whule() loop block)
// will only execute if num is > 0.
++num) // if num was > 0 then this loop will run until num overflows...
Removing the for(;;) statement will make your program run a lot better.
Your o++ has nothing do with it.
(Perhaps you have been so convinced about that being the problem that you didn't think of looking elsewhere. It happens to everyone.)
The problem is that your sequence is this:
Check the most recently entered number and print the result
Ask the user for a number, but don't do anything with it
Ask the user whether they want to continue
If they want to continue, repeat from item 1
If they don't, stop counting
And since you stop counting if the user doesn't want to continue, the last number seems to have disappeared.
Fixing it left as an exercise.
(Think more carefully about which order you need to do things in.)
Handling negative numbers requires you to write some code to do that - you handle two cases of positive numbers, and one for zero, but you must have forgotten about the negatives.
Fixing this also left as an exercise.

C++ beginner, switch isn't outputting first character of string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My task is to get a string with no spaces from the user and make the computer count the number of characters, letters, numbers, and special characters (i.e. !##$%^&*) However the program seems to be skipping the first character no matter what category this character falls under. note that it does count it in the number of characters just not in its category
example:
cin >> aZ12!#
output: 6 characters, 1 letter, 2 numbers, 2 special characters.
it always skips the first character.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char str[100]; // available character string max is 99 characters
int i;
int lett;
int num;
int spec;
cout << "Please enter a continuous string of characters with no spaces" << endl ;
cout << "(example: ASO#23iow$)" << endl << endl ; //shows an example and then adds a blank line
cout << "Enter your string: " ;
cin >> str ;
cout << endl ;
while(str[i] != 0)
{
switch(str[i])
{
case '0' ... '9':
i++ && num++;
break ;
case 'a' ... 'z':
i++ && lett++;
break ;
case 'A' ... 'Z':
i++ && lett++;
break ;
default :
i++ && spec++;
}
}
cout << "your string has " << i << " characters" << endl ;
//prints the number of numbers in the string
cout << "Your string has " << num << " numbers in it." << endl ;
cout << "Your string has " << lett << " letters in it." << endl ;
cout << "Your string has " << spec << " special characters." << endl ;
return 0 ;
In your code, int i is not initialized. Using it is Undefined Behaviour.
int i = 0;
The same goes for the rest of your variables.
Also this doesnt do what you think it does:
i++ && lett++;
This is not do both operations, its a Boolean operator. It employs something called short circuiting, which means if the first part of the && evalutes to false (ie 0), then the expression must be 0 so there is no point in evaluating the rest of it (ie the lett++ part). So for your first loop (i == 0) your lett++ will be short circuited.
Change these to:
i++;
lett++;
If you fix this up it will work:
Live example

Why the setprecision do error ? and what is setprecision

My teacher gave me this and I got an error when adding
«setprecision(3) <<setiosflags(ios::fixed) »
Could you tell me why?
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
main()
{
float x1,y1,x2,y2,x3,y3,x4,y4,PQ,QR,RS,SP,Keliling;
cout << "Masukkan koordinat empat titik berbeda (x,y) :\n";
cout<< "P(x,y):" ;
cin >> x1>>y1 ;
cout <<"\n" ;
cout << "Q(x,y) :" ;
cin >> x2>>y2 ;
cout <<"\n" ;
cout << "R(x,y) :" ;
cin>> x3>>y3 ;
cout <<"\n" ;
cout << "S(x,y) :" ;
cin >>x4>>y4;
cout <<"\n" ;
PQ = sqrt(pow(x2-x1,2)+pow(y2-y1,2));
QR = sqrt(pow(x3-x2,2)+pow(y3-y2,2));
RS = sqrt(pow(x4-x3,2)+pow(y4-y3,2));
SP = sqrt(pow(x1-x4,2)+pow(y1-y4,2));
Keliling = PQ+QR+RS+SP;
cout << "Kelilingnya adalah " << Keliling <<" satuan";
«setprecision(3) <<setiosflags(ios::fixed) »
return 0 ;
}
Because you misunderstood the instruction. You can't just dump it onto its own line in code at the end of your program and expect it to magically work, and you can't keep the French quotation marks on it.
You need to think logically about what your program does, and in what order. What do you want to accomplish, and how can you tell the computer how to help you accomplish it?
A good start would be Googling setprecision to find out what it is and how to use it.
Furthermore, your program has other problems, such as the missing return type for main.
sestprecision is a manipulator that you can pass into cout stream to define how many digits after comma should be displayed so for example:
cout << setprecision(2) << 0.122312 << endl;
will result with
0.12
it causes error because you have not put it into stream but nowhere - it is not a statement!
The problem with the line is that it is not a valid cpp statement
the setprecision statement need to be connected to an output stream and since you are using the standard output. The correction will go like this
cout << setprecision(2) << fixed << endl;
Again just as preferencebean stated, your main function should include a return type.
int main()
{
//code;
}

Formatting columns in C++

I have the following program that generates a multiplication table. A formatting problem arises when the outputs reach the double digits. How do I straighten out the columns?
#include <iostream>
using namespace std ;
int main()
{
while (1 != 2)
{
int column, row, c, r, co, ro;
cout << endl ;
cout << "Enter the number of columns: " ;
cin >> column ;
cout << endl ;
cout << "Enter the number of rows: " ;
cin >> row ;
cout << endl ;
int temp[column] ;
c = 1 ;
r = 1 ;
for(ro = 1; ro < row ; ro ++ ){
for(co = 1; co < column ; co ++ ){
c = c ++ ;
r = r ++ ;
temp [c]= co * ro;
cout << temp[c] << " ";
}
cout << endl ;
}
system("pause");
}
}
C++ had setw and setfill for just this purpose. setw sets the width and setfill sets the fill character.
In your case, you can just use something like:
#include <iostream>
#include <iomanip>
int main (void) {
std::cout << std::setw(5) << 7 << std::endl; // will output " 7".
return 0;
}
You have a number of other problems with that code, at least some of which are listed below:
You don't allocate enough space for your array, it should be column*row (or use a two-dimensional array).
Array indexes start at 0, not 1.
c = c++ is not a good idea, c++ will be enough to increment c.
You may be trying to increment c twice in each iteration, once if the for statement itself and once in the for body.
system("pause"); is an ugly hack where the language provides a perfectly good getchar or cin equivalent.
while (1 != 2) just looks plain wrong :-) since 1 will never equal 2. Just use while (1) or for(;;) - any coder worth their salt will know what you mean.
use the setw output manipulator:
cout << setw(3) << temp[c];
By default, this uses spaces to fill, which it looks like you want.
You will need to include iomanip as the documentation says.
You can set width of your column elements by using stream manipulators like this:
cout << setw(3) << temp[c]
But this is something you need to fix besides: c = c++; does not increment the variable!
This is one of those situations where the old-fashioned printf is a lot easier than cout. Replace cout << temp[c] << " " with printf("%2d ", temp[c]).
And I hope you've discovered the bug in your c calculation.
You could use "\t" instead of " ".

First while loop's first iteration always fails to take input. 2+ loops work fine

The bug starts at cin.getline ( string, 25, '\n' ); or the line below it (strtod). If I use cin, it works, except I cannot quit out. If I type anything that's not a double, an infinite loop runs. Need help. Basically, the first iteration runs, does not ask for input, so the user gets the math questions wrong. The second iteration works fine. And the next is fine, too. If I back out, using q, I get dumped back to the mode-chooser. After choosing a mode, the bug reappears for the first iteration. Next iterations it's gone.
int main()
{
char choice, name[25], string[25], op;
int operator_number, average, difference, first_operand, second_operand, input, answer, total_questions = 0, total_correct = 0;
double dfirst_operand, dsecond_operand, dinput, danswer, percentage;
bool rounding = false;
srand ( time(NULL) );
cout << "What's your name?\n";
cin.getline ( name, 25, '\n' );
cout << '\n' << "Hi, " << name << ".";
do {
do {
cout << "\nWhich math operations do you want to practice?\n 1. Addition\n 2. Subtraction\n 3. Multiplication\n 4. Division\n 5. Mixed\n 6. Difference of squares multiplication.\nChoose a number (q to quit).\n";
cin >> choice;
} while( choice < '1' || choice > '6' && choice!= 'q');
cout << "\n";
switch(choice) {
case '1':
while( string[0]!= 'q') {
dfirst_operand = rand() % 15 + 1;
dsecond_operand = rand() % 15 + 1;
danswer = dfirst_operand + dsecond_operand;
cout << dfirst_operand << " + " << dsecond_operand << " equals?\nEnter q to quit.\n";
cin.getline ( string, 25, '\n' );
dinput = strtod( string,NULL);
//cin >> dinput;
if(string[0]!='q') {
++total_questions;
if(dinput==danswer) {
++total_correct;
cout << "Correct. " << total_correct << " correct out of " << total_questions << ".";
} else {
cout << "Wrong. " << dfirst_operand << " + " << dsecond_operand << " equals " << danswer << ".\n" << total_correct << " correct out of " << total_questions << ".";
};
percentage = floor(10000 * (float) total_correct / total_questions)/100;
cout << ' ' << percentage << "%.\n\n";
}
}
break;
}
} while(choice!='q');
return 0;
}
The problem is this line:
cin >> choice;
This line parses the input buffer for character input that can be converted to an integer. So if you enter:
2<newline>
The string "2" is converted, and <newline> remains in the input buffer; so the subsequent cin.getline() is satisfied immediately.
This is also why JonH's suggestion does not work, you need to purge the input buffer after the cin << choice input. An alternative is to use cin.getline() for all input (or better; use ::getline() which operates on std::string rather than C-strings), and then parse that input using a std::istringstream object when you need formatted input scanning.
However if you must use cin.ignore() to solve this problem, you should do it thus:
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ) ;
where std::numeric_limits is defined in the header. Your solution trusts the user not to enter more than 25 characters. That is not a very safe assumption.
Try to throw a cin.ignore() right after or before the cin.getline().