[英]C++ set a char value to a string?
無論用戶選擇是否鍵入小寫字母,這都會輸出大寫字母“ 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';
}
我嘗試過進餐=“標准”,進餐=“高級”,它不起作用。
聲明額外的可變string mealTitle;
,然后執行if (meal == 'P') mealTitle = "Premium"
#include <string>
#include <cstdio>
#include <iostream>
using namespace std;
int main(void) {
string s = "Premium";
cout << s;
}
#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;
}
您不能將變量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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.