Character in Switch-Statement C++ - c++

Please help! I can't produce the output of my program. This is the condition:
Construct a program that gives a discount of 100 pesos if the shirt bought is XL and the the price is greater than 500; and a discount of 50 pesos if the shirt bought is L and the price is greater than 600.
#include <iostream>
using namespace std;
int main()
{
int p;
int s;
cout << "Input price: ";
cin >> p;
cout << "Input size: ";
cin >> s;
switch (s)
{
case 'XL': case 'xl':
{
if (p>500){
cout << "Total price: " << p-100 << " pesos.";
break;
}
else if ((s=='XL' || s=='xl') && (p<500)){
cout << "Total price: " << p << " pesos.";
break;
}
}
case 'L': case 'l':
{
if (p>600){
cout << "Total price: " << p-50 << " pesos.";
break;
}
else if ((s=='XL' || s=='xl') && (p<600)){
cout << "Total price: " << p << " pesos.";
break;
}
}
case 'M': case 'm':
{
cout << "Total price: " << p << " pesos.";
break;
}
case 'S': case 's':
{
cout << "Total price: " << p << " pesos.";
break;
}
}
return 0;
}
The output of the program:
Input price: 500
Input size: XL
Process returned 0 (0x0) execution time : 5.750 s
Press any key to continue.
P.S. How can I remove the warning (multi-character character constant) in my program?
Thanks in advance!

If the size can be more than a single character, then you'll need to represent it with a string. You can't switch on a string, so you'll have to use if..else..else.. to deal with the value:
std::string size;
cin >> size;
if (size == "XL") {
// deal with size XL
} else if (size == "L") {
// deal with size L
} // and so on
If it were a single character, then you could use char (not int) to represent that:
char size;
cin >> size;
switch (size) {
case 'L':
// deal with size L
break;
// and so on
}
but for multiple characters, you'll need a string.

switch statement can handle int and char in C++. char data type can hold only one letter. Thus, if you input only one letter (X) for XL size will be fine ...
cout << "Input size (X/L/M/S): ";
cin >> s;
switch (s){
case 'X': case 'x':

You've declared s as an integer but attempt to use it as a character and character array. You should probably declare it is char s; and then use it consistently as just a single character -- which does mean that you can't check for XL. You could, however, just check for X in your switch.
If you absolutely must check for XL, then you'll need to use either a character array or std::string, although switch statements can only be used with single characters, so you may have to nest your switch to check for multiple characters or just use a series of if (strncmp(...)...) calls.

Related

average is outputting as inf

I am trying to calculate the average for a class from scores given using a data file that was given.
The formula I'm using is grade_Average = sum / i;
The data file that was given is :
Joe Johnson 89
Susie Caldwell 67
Matt Baker 100
Alex Anderson 87
Perry Dixon 55
The output I am getting is
Johnson,Joe B
Caldwell,Susie D
Baker,Matt A
Anderson,Alex B
Dixon,Perry F
Class average inf
I am not sure if I have the formula wrong or if the formula is in the wrong place.
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
// Variable declarations:
string fName[10];
string lName[10];
float grade_Average;
string file;
string name;
int scores[10];
float sum = 0;
char grade;
int i = 0;
ifstream din;
// Function body:
cout << "Enter the name of the file. " << endl;
cin >> file;
din.open(file.c_str());
if (!din)
{
cout << " Cannot open the input file. Please try again." << endl;
return 0;
}
cout << setw(10) << setfill(' ') << "Name" <<setw(20)<<setfill(' ')<< "Grade" << endl;
while (!din.eof())
{
din >> fName[i];
din >> lName[i];
din >> scores[i];
sum = sum + scores[i];
switch (static_cast<int> (scores[i]/10))
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
grade = 'F';
break;
case 6:
grade = 'D';
break;
case 7:
grade = 'C';
break;
case 8:
grade = 'B';
break;
case 9:
grade = 'A';
break;
case 10:
grade = 'A';
break;
default:
cout << "Invalid score." << endl;
i++;
}
name = lName[i] + ',' + fName[i];
cout << setw(10) << setfill(' ') << name << setw(20) << setfill(' ')<<(" ") << grade << endl;
}
grade_Average = sum / i;
cout << "Class average " << grade_Average << endl;
din.close();
return 0;
}
Your i++ is inside the default block. The i variable is most probably 0. Either you put i++ outside of the switch block or you put it before every break statement.
i++ is inside the switch block and in the default case. It will never be executed for the given input. Therefore throughout the run i will just be 0. Dividing by 0 gives you inf.
Your program will also fail if more than 10 entries are given (and the first issue is corrected). You should use std::vector<std::string>, std::vector<int> and push_back instead of the raw arrays of std::string and int, if these arrays are needed at all. (For just calculating the average, the individual entries don't really need to be saved.)

How to add char directly after (cin) in c++

I am trying to add a percent sign directly after a users input (so that the user doesn't have to type the percent symbol). When I try this, it either goes to the next line or doesn't work at all.
What I want: _%
// the blank is for the user's input.
Sorry if this is messy, I'm not sure how to add c++ here.
Here are some things that I have attempted:
// used a percent as a variable:
const char percent = '%';
cout << "Enter the tax rate: " << percent; // obviously here the percent
symbol goes before the number.
double taxRate = 0.0;
cin >> taxRate >> percent; // here I tried adding it into the cin after the cin.
cin >> taxRate >> '%'; // here I tried adding the char itself, but yet another failed attempt...
So, is it even possible to do what I am wanting?
It is definitely possible, however iostream does not really provide a proper interface to perform it. Typically achieving greater control over console io requires use of some platform-specific functions. On Windows with VS this could be done with _getch like this:
#include <iostream>
#include <string>
#include <conio.h>
#include <iso646.h>
int main()
{
::std::string accum{};
bool loop{true};
do
{
char const c{static_cast<char>(::_getch())};
switch(c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
// TODO limit accumullated chars count...
accum.push_back(c);
::std::cout << c << "%" "\b" << ::std::flush;
break;
}
case 'q':
{
loop = false;
accum.clear();
break;
}
case '\r': // Enter pressed
{
// TODO convert accumullated chars to number...
::std::cout << "\r" "Number set to " << accum << "%" "\r" "\n" << ::std::flush;
accum.clear();
break;
}
default: // Something else pressed.
{
loop = false;
accum.clear();
::std::cout << "\r" "oops!! " "\r" << ::std::flush;
break;
}
}
}
while(loop);
::std::cout << "done" << ::std::endl;
return(0);
}
I have been having the same prob but I found an alternative, it doesn't automatically put % sign but it can let you add the %sign right after the cin without messing up when you run the code :> this is my homework, hope it helps as an example:
enter image description here
and here's what the output looks like:enter image description here
//Program that computes the total amount of savings after being invested
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
char percent [1];
float IR, IRp, TC, P, I, A;
cout << "Investment Rate:" << setw(10) << left << "";
cin>> IR >> percent;
IRp = IR*.01;
cout << "Times Compounded: " <<setw(10)<<""; //TC
cin>> TC;
cout<<"Principal:" << setw(13) << right << "$"; //P
cin>> P;
A = P*(pow(1 + (IRp/TC), TC));
I=A-P;
cout<<"Interest: " <<setw(15)<<"$ " <<fixed<<setprecision(2)<<I<<endl;
cout<< "Amount in Savings:" <<setw(5)<<"$"<<fixed<<setprecision(2)<<A<<endl;
return 0;

Unable to understand the flow of the program

I am unable to understand as to why the switch block is not executed. I am trying to generate random numbers between 0 and 2 using rand() within comp_in() function. I return the number to the main function. Within the main function, I am trying to associate a char to each letter generated. The switch statement is not executed at all. Please help!
#include<iostream>
using namespace std;
int comp_in();
int main()
{
char h;
h = human_in();
int c = comp_in();
cout << "c is" << c << endl;
switch(c)
{
case '0' : cout << "Computer's choice is : 'R'" << endl;
break;
case '1' : cout << "Computer's choice is : 'P'" << endl;
break;
case '2' : cout << "Computer's choice is : 'S'" << endl;
break;
}
}
int comp_in()
{
int s;
for(int i=0; i<4; i++)
{
s=rand()%3;
}
cout << "s is : " << s << endl;
return s;
}
Output:-
s is : 1
c is1
The problem is that your comp_in function returns numbers, but your switch is comparing its result to characters. Simply remove the single quotes from each case, making them numbers, and it'll work:
switch(c)
{
case 0 : cout << "Computer's choice is : 'R'" << endl;
break;
case 1 : cout << "Computer's choice is : 'P'" << endl;
break;
case 2 : cout << "Computer's choice is : 'S'" << endl;
break;
default: cout << "Computer made a really strange choice: " << c << endl;
break;
}
Do note that at some point in the future, you might want to compare the human input with the computer input. Since your human_in function returns a character, you're going to have to convert it by using a function like atoi.
You can detect bugs like these more quickly if you output some sort of debug message in a default case, which I've also included in the code sample above.

I think there's a slight mistake that my C++ textbook is giving me about switch statement

#include <iostream>
using namespace std;
int main()
{
int grade;
int aCount;
int bCount;
int cCount;
int dCount;
int fCount;
cout << "Enter the letter grades." << endl
<< "Enter the EOF character to end input." << endl;
while ((grade = cin.get()) != EOF)
{
switch (grade)
{
case 'A':
case 'a':
aCount++;
break;
case 'B':
case 'b':
bCount++;
break;
case 'C':
case 'c':
cCount++;
break;
case 'D':
case 'd':
dCount++;
break;
case 'F':
case 'f':
fCount++;
break;
case '\n':
case '\t':
case ' ':
break;
default:
cout << "Incorrect letter grade entered." << "Enter a new grade." << endl;
break;
}
}
cout << "\n\nNumber of students who received each letter grade:"
<< "\nA: " << aCount
<< "\nB: " << bCount
<< "\nC: " << cCount << "\nD: " << dCount << "\nF: " << fCount << endl;
system("PAUSE");
return 0;
}
This is an exact code provided by my C++ textbook. While I was practicing these switch statement codes by copying these codes then compile it, my Visual Studio 2010 express keep gives me an error saying that "aCount is being used without assigned..." same applies to fCount. This program should read any letter from A to F from a keyboard then increment whatever letter that was recognized. I think there should be cin>>grade somewhere in the codes but I don't find it. By the way, can "cin.get()" could work as cin>>grade??
When you are declaring your variables try giving them the value of 0 like this:
int grade = 0;
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
This will ensure that you are in fact assigning a value to the variable before it is being used.
Then try to run it, I bet it works!
It is advisable for you to initialize your variables being using it. Some compiler will not even give you a warning before compilation, but assigns some "garbage values" to your un-initialize variables.
Initializing your variables to 0 is suffice in this scenario (Like what other user mentioned).
int grade=0;
int aCount=0;
int bCount=0;
int cCount=0;
int dCount=0;
int fCount=0;
By the way, can "cin.get()" could work as cin>>grade??
That depends on how you want to use it. cin.get can be used to extract a:
single character
multiple characters and store them as c-string (char array) or
store them into a stream buffer object
from the input stream.
You may realize cin.get can't accept numbers, so if you are accepting input of characters or string, it is fine. But in future, if you want it to accept numbers, just use cin >> number
An example on using cin.get()
char cStr[50];
cin.get(cStr,5); //It will take n-1 characters
cout << cStr;
//Input: abcde
//Output: abcd

C++: Will Not Accept New C-String Input

First off, thanks in advance for your help. This issue is driving me nuts.
I have a program that accepts a c-string, and then can count the number of vowels and consonants. This works without issue. However, I also need to include a function that allows the user to create a new string. The problem is, though, when the user selects "new string" from the menu, it just loops through the newString() method, without waiting for the user's input. It then creates a new, blank screen.
Here is the entire program. The newString() method is at the end.
#include <iostream>
using namespace std;
// function prototype
void printmenu(void);
int vowelCount(char *);
int consCount(char *);
int cons_and_vowelCount(char *);
void newString(char *, const int);
int main() {
const int LENGTH = 101;
char input_string[LENGTH]; //user defined string
char choice; //user menu choice
bool not_done = true; //loop control flag
// create the input_string object
cout << "Enter a string of no more than " << LENGTH-1 << " characters:\n";
cin.getline(input_string, LENGTH);
do {
printmenu();
cin >> choice;
switch(choice)
{
case 'a':
case 'A':
vowelCount(input_string);
break;
case 'b':
case 'B':
consCount(input_string);
break;
case 'c':
case 'C':
cons_and_vowelCount(input_string);
break;
case 'd':
case 'D':
newString(input_string, LENGTH);
break;
case 'e':
case 'E':
exit(0);
default:
cout << endl << "Error: '" << choice << "' is an invalid selection" << endl;
break;
} //close switch
} //close do
while (not_done);
return 0;
} // close main
/* Function printmenu()
* Input:
* none
* Process:
* Prints the menu of query choices
* Output:
* Prints the menu of query choices
*/
void printmenu(void)
{
cout << endl << endl;
cout << "A) Count the number of vowels in the string" << endl;
cout << "B) Count the number of consonants in the string" << endl;
cout << "C) Count both the vowels and consonants in the string" << endl;
cout << "D) Enter another string" << endl;
cout << "E) Exit the program" << endl;
cout << endl << "Enter your selection: ";
return;
}
int vowelCount(char *str) {
char vowels[11] = "aeiouAEIOU";
int vowel_count = 0;
for (int i = 0; i < strlen(str); i++) {
for (int j = 0; j < strlen(vowels); j++) {
if (str[i] == vowels[j]) {
vowel_count++;
}
}
}
cout << "String contains " << vowel_count << " vowels" << endl;
return vowel_count;
} // close vowelCount
int consCount(char *str) {
char cons[43] = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
int cons_count = 0;
for (int i = 0; i < strlen(str); i ++) {
for (int j = 0; j < strlen(cons); j++) {
if (str[i] == cons[j]) {
cons_count++;
}
}
}
cout << "String contains " << cons_count << " consonants" << endl;
return cons_count;
} // close consCount
int cons_and_vowelCount(char *str) {
int cons = consCount(str);
int vowels = vowelCount(str);
int total = cons + vowels;
cout << "The string contains a total of " << total << " vowels and "
"consonants" << endl;
return total;
}
void newString(char *str, int len) {
cout << "Enter a string of no more than " << len-1 << " characters:\n";
cin.getline(str, len);
return;
}
The statement cin >> choice only consumes the character they type, not the carriage return that follows. Thus, the subsequent getline() call reads an empty line. One simple solution is to call getline() instead of cin >> choice and then use the first character as the choice.
BTW, the while (not done) should immediately follow the do { … }, and the return 0 is redundant. Also, you should call newString at the start of the program instead of repeating its contents.
cin >> choice leaves a newline in the input stream.. which cause the next getline() to consume it and return. There are many ways.. one way is to use cin.ignore() right after cin >> choice.
The cin >> choice only consumes one character from the stream (as already mentioned). You should add
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
right after cin>>choice to ignore all the characters that come into the stream after reading the choice.
p.s. #include <limits>