C ++将char值设置为字符串?

时间:2014-01-25 12:23:10

标签: c++ string if-statement char

这输出大写' S'或者' P'无论用户选择是否输入小写。 当我在我的代码中使用其他语句时,输出有效 但是......我想在最后的cout声明中显示STANDARD或PREMIUM。

如何更改char的值以输出STANDARD或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';
}

我尝试过用餐=&#39;标准版&#39;和饭=&#39; Premium&#39; 它没有用。

4 个答案:

答案 0 :(得分:1)

声明额外变量string mealTitle;,然后执行if (meal == 'P') mealTitle = "Premium"

#include <string>
#include <cstdio>
#include <iostream>
using namespace std;
int main(void) {
        string s = "Premium";
        cout << s;
}

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您无法将变量meal更改为字符串,因为其类型为char。只需使用另一个具有不同名称的对象:

std::string meal_type;
switch (meal) {
case 'P':
    meal_type = "Premium";
    break;
case 'S':
default:
    meal_type = "Standard";
    break;
}

答案 3 :(得分:0)

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