【问题标题】:C++ set a char value to a string?C ++将char值设置为字符串?
【发布时间】:2014-02-16 11:56:45
【问题描述】:

无论用户是否选择输入小写字母,这都会输出大写字母“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';
}

我尝试过膳食 = '标准' 和膳食 = '高级' 它不起作用。

【问题讨论】:

  • chars 不是 strings 和 strings 不是 chars... 'Standard' 两者都不是(您正在尝试使用 char 语法定义字符串) .决定你想要哪个,如果需要,声明 两个 变量!
  • if (meal == 'S') { meal = 'S'; } 似乎毫无意义。
  • 好吧,我已经尝试过膳食 = '标准',但没有奏效。它只输出最后一个字母'd'

标签: c++ string if-statement char


【解决方案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;
}

【讨论】:

  • 我试过这个并且它有效,但我不明白为什么这些值设置为 *char meal = '\0' (这是为了什么?)
【解决方案2】:

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

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

【讨论】:

  • 刚刚尝试过,但仍然只能得到输出'S'或'P'
  • 你试过cout &lt;&lt; mealTitle吗?
  • 我的变量都被扭转了。我想我现在明白了,谢谢
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:
    #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;
    }
    

    【讨论】:

    • 抱歉我只懂C++
    • 我写的怎么不是C++?
    猜你喜欢
    • 2013-05-13
    • 2013-04-01
    • 2018-09-02
    • 2018-03-27
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多