C 将字符值设置为字符串
C++ set a char value to a string?
这将输出上情况'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;
}
相关文章:
- C++ 命名参数习惯用语 - 未设置字符串属性
- 如何将字符串属性设置为 QTreeWidgetItem?
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- C++如何将字符串数组中的一个点设置为枚举变量
- 从C++为字符串函数设置_ENV
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 通过比较字符设置字符串时出现问题
- 如何在 c++ 中从字符串向量设置类对象
- STD ::设置带有字符串键和潜在效率损失
- 如何调用 GetAltMonthNames 来填充外部区域设置月份字符串的安全数组
- 设置可变值通过字符串引用它
- 仅使用 getName 在主函数中设置字符串名称
- 如何将变量名设置为字符串?C++
- 在类中设置Arduino字符串值
- 如何在C++中有条件地设置 C 样式字符串?
- 在字符串列表中查找字符串,然后将字符串设置为找到的字符串?
- 从函数参数常量字符串 (&) 设置值
- 在定义过程中将std::string设置为0与将std::字符串设置为0相比
- 将字符串设置为日期格式
- 如何将包含空格的字符串设置为HTML文本字段(在表单中)的默认值