This outputs upper case 'S' or 'P' regardless of the users choice to type lower case or not.
The output works when I cout with the other statements in my code
HOWEVER... I want to display STANDARD or PREMIUM in my final cout statement.
How can I change the value of the char to output either STANDARD or PREMIUM???
#include <string>
#include <iostream>
char meal;
cout << endl << "Meal type: standard or premium (S/P)? ";
cin >> meal;
meal = toupper(meal);
if (meal == 'S'){
meal = 'S';
}
else{
meal = 'P';
}
I've tried meal = 'Standard' and meal = 'Premium'
It doesn't work.
#include<iostream>
#include<string>
using namespace std;
int main(int argc, char* argv)
{
char meal = '\0';
cout << "Meal type: standard or premium (s/p)?" << endl;;
string mealLevel = "";
cin >> meal;
meal = toupper(meal);
if (meal == 'S'){
mealLevel = "Standard";
}
else{
mealLevel = "Premium";
}
cout << mealLevel << endl;
return 0;
}
declare extra variable string mealTitle;, then do if (meal == 'P') mealTitle = "Premium"
#include <string>
#include <cstdio>
#include <iostream>
using namespace std;
int main(void) {
string s = "Premium";
cout << s;
}
You cannot change the variable meal to be a string, because its type is a char. Just use another object with a different name:
std::string meal_type;
switch (meal) {
case 'P':
meal_type = "Premium";
break;
case 'S':
default:
meal_type = "Standard";
break;
}
#include <string>
#include <iostream>
std::string ask() {
while (true) {
char c;
std::cout << "\nMeal type: standard or premium (S/P)? ";
std::cout.flush();
if (!std::cin.get(c)) {
return ""; // error value
}
switch (c) {
case 'S':
case 's':
return "standard";
case 'P':
case 'p':
return "premium";
}
}
}
int main() {
std::string result = ask();
if (!result.empty()) {
std::cout << "\nYou asked for " << result << '\n';
} else {
std::cout << "\nYou didn't answer.\n";
}
return 0;
}
Related
This program is essentially supposed to count the results of random throws of a dice 100 times and count the occurrence of each face then display all of them as a histogram of asterisks. It would seem the functions could be working but i'm unable to verify because after I make my choice, nothing displays.
#include <iostream>
#include <iomanip>
#include <string>
#include <random>
#include <sstream>
using namespace std;
enum class Side {
ONE, TWO, THREE, FOUR, FIVE, SIX
};
struct Bar {
int value;
Side label;
};
//roll dice function
void rollDice( Bar h[], int n = 100);
void rollDice( Bar h[], int){
default_random_engine en;
uniform_int_distribution<> dist{1,6};
int results[] ={0,0};
for( int n; n<=100; n++){
cout << dist(en);
results[dist(en)]++;
h[n].value = results[n];
if(h[n].value == 1){
h[n].label = Side::ONE;
}
else if(h[n].value == 2){
h[n].label = Side::TWO;
}
else if(h[n].value == 3){
h[n].label = Side::THREE;
}
else if(h[n].value == 4){
h[n].label = Side::FOUR;
}
else if(h[n].value == 5){
h[n].label = Side::FIVE;
}
else {
h[n].label = Side::SIX;
}
}
};
string getHistogram(Bar h[], char c = '*');
string getHistogram(Bar h[], char c ){
stringstream ast;
for( int n; n<=100; n++){
switch (h[n].label)
{
case Side::ONE:
return to_string(c);
break;
case Side::TWO:
return to_string(c);
break;
case Side::THREE:
return to_string(c);
break;
case Side::FOUR:
return to_string(c);
break;
case Side::FIVE:
return to_string(c);
break;
case Side::SIX:
return to_string(c);
break;
default:
break;
}
}
ast << "One: " << c << endl;
ast << "Two: " << c << endl;
ast << "Three: " << c << endl;
ast << "Four: " << c << endl;
ast << "Five: " << c << endl;
ast << "Six: " << c << endl;
string output = ast.str();
cout<< output;
return output;
}
int main (){
Bar histogram[] = {
{0,Side::ONE},{0,Side::TWO}, {0,Side::THREE},
{0,Side::FOUR},{0,Side::FIVE}, {0,Side::SIX}
};
char choice;
do {
cout << "DICE ROLLING SIMULATION" << endl
<<"===============================" << endl
<< "r. Roll Dice" << endl
<< "h. Display histogram" << endl
<< "q. Quit program\n" << endl
<< "\nEnter your choice:" << endl;
// Reading a single character using the scanner
cin >> choice;
switch(choice) {
case 'r': case 'R':
rollDice(histogram, 100);
break;
case 'h': case 'H':
cout<< getHistogram(histogram, '*');
break;
case 'q': case 'Q':
cout << "Good bye\n" << endl;
break;
default:
cout << "Invalid choice\n" << endl;
}
} while(choice != 'q');
}
So, this code contains many different mistakes. Let's go in order.
In structBar label may be const
struct Bar {
int value;
const Side label;
};
You don't need forward declaration for function signature
In rollDice you have many unnecessary local variables and I would use mt19937 random generator. So rollDice will look like this
void rollDice(Bar h[], int count = 100) {
default_random_engine en;
uniform_int_distribution<> dist{1,6};
for( int n = 0; n <= count; n++) {
cout << dist(en) << endl;
const auto index = dist(en) - 1;
++h[index].value;
}
};
In getHistogram you have return to_string(c); in switch therefore you don't see histogram. You can delete swith because you can match index and Side. And why cycle up to 100?
string getHistogram(Bar h[], char c = '*') {
stringstream ast;
for( int n = 0; n <= 5; n++) {
const string strValue = string(h[n].value, c);
switch (h[n].label)
{
case Side::ONE: ast << "One: "; break;
case Side::TWO: ast << "Two: "; break;
case Side::THREE: ast << "Three: "; break;
case Side::FOUR: ast << "Four: "; break;
case Side::FIVE: ast << "Five: "; break;
case Side::SIX: ast << "Six: "; break;
}
ast << strValue << '(' << h[n].value << ')' << endl;
}
return ast.str();
}
In main function you have to clear histogram before next rollDice
case 'r': case 'R':
for (Bar& b : histogram) {
b.value = 0;
}
rollDice(histogram, 100);
break;
Full version
#include <iostream>
#include <iomanip>
#include <string>
#include <random>
#include <sstream>
using namespace std;
enum class Side {
ONE, TWO, THREE, FOUR, FIVE, SIX
};
struct Bar {
int value;
Side label;
};
void rollDice(Bar h[], int count = 100) {
default_random_engine en;
uniform_int_distribution<> dist{1,6};
for( int n = 0; n <= count; n++) {
cout << dist(en) << endl;
const auto index = dist(en) - 1;
++h[index].value;
}
};
string getHistogram(Bar h[], char c = '*') {
stringstream ast;
for( int n = 0; n <= 5; n++) {
const string strValue = string(h[n].value, c);
switch (h[n].label)
{
case Side::ONE: ast << "One: "; break;
case Side::TWO: ast << "Two: "; break;
case Side::THREE: ast << "Three: "; break;
case Side::FOUR: ast << "Four: "; break;
case Side::FIVE: ast << "Five: "; break;
case Side::SIX: ast << "Six: "; break;
}
ast << strValue << '(' << h[n].value << ')' << endl;
}
return ast.str();
}
int main (){
Bar histogram[] = {
{0, Side::ONE},
{0, Side::TWO},
{0, Side::THREE},
{0, Side::FOUR},
{0, Side::FIVE},
{0, Side::SIX}
};
char choice;
do {
cout << "DICE ROLLING SIMULATION" << endl
<<"===============================" << endl
<< "r. Roll Dice" << endl
<< "h. Display histogram" << endl
<< "q. Quit program\n" << endl
<< "\nEnter your choice:" << endl;
// Reading a single character using the scanner
cin >> choice;
switch(choice) {
case 'r': case 'R':
for (Bar& b : histogram) {
b.value = 0;
}
rollDice(histogram, 100);
break;
case 'h': case 'H':
cout << getHistogram(histogram, '*') << endl;
break;
case 'q': case 'Q':
cout << "Good bye\n" << endl;
break;
default:
cout << "Invalid choice\n" << endl;
}
} while(choice != 'q');
}
In my class one of our assignments is to convert a prefix equation to infix. After reading that section I still have no idea what I'm doing. The book had some code that will solve a prefix equation when given but I have no idea how it does it or how I would display the infix version. Any help would be appreciated in explaining how this code finds the solution and how I could have it display a infix version.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;
int prefixExpr(istream &exprStream);
int main() {
string input;
cout << "Enter prefix expressions to evaluate. \nPress enter after each expression, and press enter on a blank line to quit." << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
while (input.size() != 0){
istringstream exprStream(input);
cout << prefixExpr(exprStream) << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
}
return 0;
}
int prefixExpr(istream &exprStream) {
char ch = exprStream.peek();
while (isspace(ch)) {
ch = exprStream.get();
ch = exprStream.peek();
}
cout << ch << endl;
if (isdigit(ch)) {
int number;
exprStream >> number;
cout << number << endl;
return number;
}
else {
ch = exprStream.get();
int value1 = prefixExpr(exprStream);
int value2 = prefixExpr(exprStream);
switch (ch) {
case '+': return value1 + value2;
case '-': return value1 - value2;
case '*': return value1 * value2;
case '/': return value1 / value2;
default: cout << "Bad input expression";
exit(1);
}
}
}
I'm kinda new to C++ and I'm having an hard time with a little ""game"" I'm making.
Here I'm tryng to create a sort of menu that you can move through using the Arrow keys as inputs, and confirm using the Enter key, but despite not getting any error in the compiler the program just closes itself when I reach the second Switch Case.
What am I doing wrong? Thanks
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <windows.h>
#include <conio.h>
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
#define ENTER 13
using namespace std;
int main()
{
struct Stats {
int Hp;
int Atk;
int Speed;
int Defense;
};
struct Defense {
bool IsWeakFire;
bool IsWeakIce;
bool IsWeakWind;
bool IsWeakElectric;
bool IsWeakLight;
bool IsWeakDark;
};
struct CharacterStats {
string Name;
string Desc;
string Persona;
Stats Stats;
Defense Defense;
}Characters[4];
//Program Start
cout << "You are now playng: ProjectPB \n" << endl <<
"MC Name> ";
cin >> Characters[0].Name;
cout << "\n \n The game will now start.";
for (int i=0;i<4;i++)
{
Sleep(500);
cout << ".";
}
system("cls");
//Fight start
int i = 0;
int sel = 1;
int c = 0;
while (i == 0) {
switch (sel)
{
case 1:
system("cls");
cout << " |ATTACK| PERSONA DEFEND" << endl;
system("pause");
break;
case 2:
system("cls");
cout << " ATTACK |PERSONA| DEFEND" << endl;
system("pause");
break;
case 3:
system("cls");
cout << " ATTACK PERSONA |DEFEND|" << endl;
system("pause");
} break;
Sleep(100);
int i = 0;
int sel = 1;
while (i == 0){
switch (sel)
{
case 1:
system("cls");
cout << " |ATTACK| PERSONA DEFEND" << endl;
system("pause");
break;
case 2:
system("cls");
cout << " ATTACK |PERSONA| DEFEND" << endl;
system("pause");
break;
case 3:
system("cls");
cout << " ATTACK PERSONA |DEFEND|" << endl;
system("pause");
} break;
Sleep(100);
int c = _getch();
switch (c)
{
case KEY_LEFT :
sel--;
if (sel <= 0)
{
sel = 3;
}
break;
case KEY_RIGHT :
sel++;
if (sel > 3)
{
sel = 1;
}
break;
case ENTER:
i = 1;
break;
}
}
}
return 0;
}
This must be because of the non-empty input buffer during this statement
int c = _getch();
To solve this,simply clear the buffer with this right before getch()
while ((getchar()) != '\n');
I'm trying to learn C++ and i cant figure a problem out.
My code:
#include <iostream>
using namespace std;
int userContinue = true;
int userContinueString;
int getUserInput() {
int userInput1;
int userInput2;
cout << "Please enter your first number: ";
cin >> userInput1;
cout << endl << "Please enter your second number: ";
cin >> userInput2;
cout << endl << "The result of the two numbers together: " << userInput1+userInput2;
userInput1 = 0;
userInput2 = 0;
return 0;
}
int main()
{
while (userContinue == true) {
getUserInput();
cout << endl << "Would you like to continue? (Y/N): ";
cin >> userContinueString;
if (userContinueString ='Y') {
}
else {
userContinue = false;
}
}
return 0;
}
The code works fine until i input "Y" ant then it keeps looping as shown here: Video
First, make sure you compile your code with some warning switches such as -Wall -Wpedantic. These switches will help you. For instance, in your original code, my compiler prints the following warnings:
prog.cpp:25:28: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if (userContinueString = 'Y') {
~~~~~~~~~~~~~~~~~~~^~~~~
prog.cpp:25:28: note: place parentheses around the assignment to silence this warning
if (userContinueString = 'Y') {
^
( )
prog.cpp:25:28: note: use '==' to turn this assignment into an equality comparison
if (userContinueString = 'Y') {
^
==
1 warning generated.
Then, I fix the corresponding line with ==, which was already suggested in the comments. Then, your comparison should be case-insensitive. Finally, you would like to compare character objects with respect to 'y' or 'Y':
#include <cctype>
#include <iostream>
using namespace std;
int userContinue = true;
char /* not int */ userContinueString;
int getUserInput() {
int userInput1;
int userInput2;
cout << "Please enter your first number: ";
cin >> userInput1;
cout << endl << "Please enter your second number: ";
cin >> userInput2;
cout << endl
<< "The result of the two numbers together: " << userInput1 + userInput2;
userInput1 = 0;
userInput2 = 0;
return 0;
}
int main() {
while (userContinue == true) {
getUserInput();
cout << endl << "Would you like to continue? (Y/N): ";
cin >> userContinueString;
if (std::tolower(userContinueString) == 'y') {
} else {
userContinue = false;
}
}
return 0;
}
EDIT. I have improved the answer by taking into account David's comment below. Note the use of #include <cctype> and std::tolower.
EDIT. I have tried improving the answer further by trying to address the "learning C++" comment below:
#include <functional>
#include <iostream>
#include <sstream>
#include <string>
#include <type_traits>
template <class value_t,
typename std::enable_if<std::is_floating_point<value_t>::value,
int>::type = 0>
struct Calculator {
Calculator() = default;
explicit operator bool() {
while (true) {
std::cout << "Valid operations: +, -, *, /, 0 (exit)\n";
std::cout << "What would you like to do: ";
if (!getUserInput(operation)) {
std::cerr << "Wrong input for operation\n";
continue;
}
switch (operation) {
case '0':
return false;
case '+':
case '-':
case '*':
case '/':
break;
default:
std::cerr << "Wrong input for operation\n";
continue;
}
std::cout << "Please enter v1: ";
if (!getUserInput(v1)) {
std::cerr << "Wrong input for v1\n";
continue;
}
std::cout << "Please enter v2: ";
if (!getUserInput(v2)) {
std::cerr << "Wrong input for v2\n";
continue;
}
calculate();
return true;
}
}
friend std::ostream &operator<<(std::ostream &os, const Calculator &c) {
os << "v1 " << c.operation << " v2 = " << c.result;
return os;
}
private:
char operation;
value_t v1, v2, result;
std::string line;
void calculate() {
switch (operation) {
case '+':
return calculate(std::plus<value_t>{});
case '-':
return calculate(std::minus<value_t>{});
case '*':
return calculate(std::multiplies<value_t>{});
case '/':
return calculate(std::divides<value_t>{});
case '0':
return;
}
}
template <class Func> void calculate(Func &&f) { result = f(v1, v2); }
template <class T> bool getUserInput(T &t) {
std::cin >> line;
std::istringstream ss{line};
return (ss >> t) && (ss >> std::ws).eof();
}
};
int main() {
Calculator<double> c;
while (c)
std::cout << c << '\n';
return 0;
}
#include <iostream>
using namespace std;
int main ()
{
char letter;
while (cin>>letter)
{
switch (letter)
{
case 'a':
cout<<"ant"<<endl;
break;
default :
cout <<"enter only lower cases letters "<<endl;
}
}
return 0;
}
Is there any feature of c++ that ignores the characters next to first character? Because i.e., if I enter aaa it displays ant ant ant, so I want to get rid of this part. I hope you get my question.
Read a string and then switch on the first character. Like this.
int main () {
string word;
while (cin >> word) {
switch (word[0]) {
case 'a':
cout << "ant" << endl;
break;
default:
cout << "enter only lower cases letters " << endl;
break;
}
}
return 0;
}
You can treat the user input as a std::string and then just look at the first character from it for your switch statement. This will ignore anything the user inputs after the first character. I can't imagine the use case for this, but I believe this is what you're asking for.
#include <cstdlib>
#include <iostream>
int main( int argc, char *argv[] )
{
std::string word;
while (std::cin >> word)
{
char letter = word[0];
switch (letter)
{
case 'a':
std::cout << "ant" << std::endl;
break;
default:
std::cout << "please enter only lower case letters" << std::endl;
break;
}
}
return EXIT_SUCCESS;
}
Read chars repeatedly and keep track of what's been added
#include <set>
int main () {
char letter;
std::set<char> used;
while (cin >> letter) {
if (!used.insert(letter)[1]) // note returns a pair; 2nd item ([1]) is true if it didn't exist before
continue;
switch (letter) {
case 'a':
cout << "ant" << endl;
break;
default:
cout << "enter only lower cases letters " << endl;
break;
}
}
return 0;
}
Only first char will be saved
int main()
{
char c = 0;
c = getchar();
putchar(c);
return 0;
}