C++:显示变量
C++: Displaying a Variable
我有一个关于C++的快速问题。我正在制作一个基于文本的游戏,我希望玩家能够输入"Score"
,它将打印当前分数(int score = 50
)。我正在使用if(Choice == 3)
表示数字,但我希望能够在输入中键入单词。
谁能帮忙?
感谢您的阅读。
std::string input;
cin >> input;
// lowercase it, for case-insensitive comparison
std::transform(input.begin(), input.end(), input.begin(), std::tolower);
if (input == "score")
std::cout << "Score is: " << score << std::endl;
使用 std::getline
将整行读入字符串,然后简单地将字符串与 ==
进行比较。
还有许多其他方法可以做到这一点,但任何不基于std::getline
的解决方案都可能是不必要的复杂。
很难
准确猜测您要做什么,但一般来说,如果要比较字符串,请使用字符串比较例程。例如
#include <iostream>
int main(void) {
std::string choice;
std::cout<<"Please enter your choice:"<<std::endl;
std::cin>>choice;
if (choice.compare("score")==0) {
std::cout << "score!" << std::endl;
}
else {
std::cout << "fail!" << std::endl;
}
}
如果使用 boost,则可以进行不区分大小写的比较。或者,您可以将输入转换为全部小写。谷歌"不区分大小写的字符串比较C ++"了解更多信息。
尝试:
std::string userInput;
// Takes a string input from cin and stores in userInput variable
getline(std::cin, userInput);
// Check if user input is "Score"
if (userInput.compare("Score") == 0)
{
std::cout << "Score = " << score << std::endl;
}
如果用户输入是"Score",那么比较将是完全匹配的,userInput.compare()将返回0,这就是为什么我们检查它是否为零。
相关文章:
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 为什么我的双变量通过添加 c++ 显示 nan?
- 类中的一个变量显示,但另一个不显示
- 变量在循环中显示,但不在循环中显示
- 显示 C++ 中"anonymous"变量创建的警告
- gdb映射显示不正确的成员变量
- 使用 while 循环显示顺序变量的值
- Eclipse 编译器有没有办法将变量中的地址字段显示为整数值?
- C++无法在对话框 CFormView 中显示 ActiveX 控件,则控件变量为 NULL
- 如何使用C++中不是文字的变量在数字中显示单引号和两个引号?假设 6'2" 英尺
- Intellisense未显示变量
- 为什么我的第二个time_t变量没有正确显示
- 在每次迭代中显示变量
- 使用全局变量显示C++在使用 pthread 时比指针慢 100%?
- GNU 调试器无法从显示中删除变量?
- 如何使 ACS 变量显示在终端上
- 为什么由指针和对象构建的局部变量显示不同的输出
- lambda 函数中的变量显示垃圾值
- 在 c++ 中使用 strcmp 比较两个 char 变量显示从 'char' 到 'const char*' 的无效转换
- 编译器编译"io_service_"变量显示为:不能出现在常量表达式中