judonomi
judonomi

Reputation: 75

C++ set a char value to a string?

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.

Upvotes: 1

Views: 494

Answers (4)

Hal Canary
Hal Canary

Reputation: 2240

#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;
}

Upvotes: 0

exebook
exebook

Reputation: 33890

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;
}

Upvotes: 1

user3228097
user3228097

Reputation: 26

#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;
}

Upvotes: 1

Shoe
Shoe

Reputation: 76240

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;
}

Upvotes: 0

Related Questions