How to add char directly after (cin) in c++ - 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;

Related

Switch Case always goes to default

I am trying to make a small operating system that takes a response from a switch...case to go to a miniature game or a simple calculator. However, no matter what input I give (even correct ones) the output is always the default.
The compiler I am using (Microsoft Visual Studio; It could be the problem) isn't giving me any errors, and I can't find or think of any mistakes. Do some of you people who are actually good at this have any answers to my problem?
#include "stdafx.h"
#include <iostream>
#include <limits>
using namespace std;
int calc() {
char op;
float num1, num2;
cout << "Enter operation:";
cin >> op;
cout << "Enter two numbers:";
cin >> num1 >> num2;
switch (op)
{
case '+':
cout << num1 + num2;
break;
case '-':
cout << num1 - num2;
break;
case '*':
cout << num1 * num2;
break;
case '/':
cout << num1 / num2;
break;
default:
cout << "That is not an operation";
break;
}
return 0;
};
int main()
{
char answer;
cout << "Welcome to the FR Operating System. \n";
cout << "If you want to go to the calculator, type in 'Calc'. \n";
cout << "If you want to go to the game, type in 'Game'. \n";
cin >> answer;
switch (answer) {
case 'Calc' || 'calc':
cout << "Welcome to the calculator. \n";
break;
case 'Game':
cout << "Welcome to our game, 'A Day in the Life'. \n";
break;
default:
cout << "That is an invalid answer. This has caused the system to crash. \n";
break;
}
atexit([] { system("PAUSE"); });
return 0;
}
'Game' is not a valid string
Even if you replace it by "Game", which is a valid string, switch doesn't work with strings.
So either use single chars in your switch or use if-else blocks where you compare std::strings via ==.
std::string answer;
cin >> answer;
if (answer == "Calc" || answer == "calc")
//...
else if (answer == "Game")
//...
else
// invalid
Use map to item callbacks
Ideally, it would be better to map item menu to it's respective actions. std::map<std::string, std::function<void()>> allows exactly that! Read the inline comments to make sense of the rest:
#include <string>
#include <map>
#include <iostream>
#include <functional>
int main()
{
std::map<std::string, std::function<void()>> menu_items;
menu_items.emplace("calc", [](){std::cout << "calculate chosen\n";}); //use lambdas to spare boilerplate
menu_items.emplace("game", [](){std::cout << "game is chosen\n";});
std::string chosen_item;
std::cin >> chosen_item;
auto item = menu_items.find(chosen_item); //search by the string
if (item == menu_items.end()) //item was not found in the list
std::cout << "invalid item is chosen\n";
else
item->second(); //execute the stored function
}
Demo.
Depending on your usage you might want to use void*() for std::function<void()>, and std::unordered_map for std::map. For your usage case it doesn't seem to matter though.
Also you might want to normalize the input, e.g. lowercase the string, or perform some other normalization. Since this is not performance sensitive part of the code, I believe overhead of std::function and std::map won't matter in this case.
You are prompting user for a string while your variable answer is a char, change your prompts to characters like c and g thus make it more convenient, thus you can use and enumerate characters in your switch / case statement:
int main()
{
char answer;
cout << "Welcome to the FR Operating System. \n";
cout << "If you want to go to the calculator, type in 'c'. \n";
cout << "If you want to go to the game, type in 'g'. \n";
cin >> answer;
switch (answer) {
case 'c':
case 'C':
cout << "Welcome to the calculator. \n";
break;
case 'g':
case 'G':
cout << "Welcome to our game, 'A Day in the Life'. \n";
break;
...

Loop in a switch case statement

I need help with validating a switch case statement i need it to check what the user has entered and if it does not match reject it and tell them to do it again. the one i have at the moment partially works but will reject the first number then break when trying to enter another number. Help If you need to see the whole program just ask.
#include "stdafx.h"
#include "cstdlib"
#include "iostream"
#include "windows.h"
#include "cmath"
using namespace std;
int main(int argc, char* argv[])
{
float ALT0();
float ALT5000();
float ALT10000();
float ALT15000();
float ALT20000();
float ALT25000();
float ALT30000();
float ALT35000();
float ALT40000();
void an_answer(float a);
char Restart;
char op;
float answer;
do
{
cout << "\n\t\t\tOperational Flight Plan\n" << endl;
cout << "For the saftey of everyone on board, there will be 100 kg added to the overall\namount to give the aircraft more fuel incase of a head on wind or delays at the landing airport.\n" << endl;
cout << "Select Altitude the aircraft will fly at: " << endl;
cout << "0 for 0ft\n1 for 5000ft\n2 for 10000ft\n3 for 15000ft\n4 for 20000ft\n5 for 25000ft\n6 for 30000ft\n7 for 35000ft\n8 for 40000ft" << endl;
cin >> op;
switch (op)
{
case'0':
answer=ALT0();
break;
case '1':
answer=ALT5000();
break;
case '2':
answer=ALT10000();
break;
case '3':
answer=ALT15000();
break;
case '4':
answer=ALT20000();
break;
case '5':
answer=ALT25000();
break;
case '6':
answer=ALT30000();
break;
case '7':
answer=ALT35000();
break;
case '8':
answer=ALT40000();
break;
default:
cout << "You must enter a number from 0-8" << endl;
cin >> op;
break;
}
an_answer(answer);
cout << "Do you want to do another calculation? Press Y for yes and anything else to quit.";
cin >> Restart;
} while (Restart=='y' || Restart=='Y');
//system("PAUSE");
//return EXIT_SUCCESS;
}
I'm betting you're hitting enter after entering the number. Your first cin >> op reads the number, but your second one reads the enter key. If you want to read in an entire line, use a function that reads in an entire line.
Alternately, move the second cin >> op up to before the switch statement. This will break if someone enters more than one character before hitting enter but will work otherwise.

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

Character in Switch-Statement 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.

writing code in enum

I wrote a certain method on how to access my fields in a class, but my teacher told me I should use an enum.
How can I re-write this code to use an enum and not use gotos?
void SetType() {
cout << "Book SetType" << endl;
Choice: cout << "Please Select from the list: \n "
<< "1- Technical literature \n "
<< "2- Fiction literature \n "
<< "3- Textbook" << endl;
int i;
cin >> i;
switch (i) {
case 1:
Type = "Technical literature";
break;
case 2:
Type = "Fiction literature";
break;
case 3:
Type = "Textbook";
break;
default:
cout << "Erorr you entered a wrong choice" << endl;
goto Choice;
}
}
just use loops instead of gotos of it is going to be a spaghetti code.
Enums are fine to does not care about the numbers for the defines, because they are incremented automatically if you add a new one.
#include <iostream>
#include <string>
void SetType();
using namespace std;
string Type;
int main()
{
SetType();
cout << "so you choose " << Type << endl;
return 0;
}
enum select
{
Technical_literature = 1,
Fiction_literature,
Textbook
};
void SetType() {
cout<<"Book SetType"<<endl;
while(1)
{
cout<<"Please Select from the list: \n 1- Technical literature \n 2- Fiction literature \n 3- Textbook"<<endl;
int i;
cin >> i;
switch(i) {
case Technical_literature:
Type="Technical literature";
return;
case Fiction_literature:
Type="Fiction literature";
return;
case Textbook:
Type="Textbook";
return;
default:
cout << "Erorr you entered a wrong choice" << endl;
}
}
}
Your teacher meant that instead of hardcoding constants all over the place you need to declare your i as enum.
enum some_type {
type_techlit=1, type_fiction, type_textbook
};
some_type i;
And then read up on enums.