C 将字符值设置为字符串

C++ set a char value to a string?

本文关键字:字符串 设置 字符      更新时间:2023-10-16

这将输出上情况's'或'p',而不管用户选择键入较低的情况如何。当我用代码中的其他语句与其他语句相提并论时,输出可以工作但是...我想在我的最终代表语句中显示标准或高级。

如何将字符的值更改为输出标准或高级?

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

我已经尝试了进餐='standard'和餐='premium'它行不通。

#include<iostream>
#include<string>
using namespace std;
int main(int argc, char* argv)
{
    char meal = '';
    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;
}

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

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

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

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