如何使变量等于C++中的字母
How to make a variable be equal to a letter in C++?
我尝试用C++制作一个简单的程序,因为我是初学者。该程序应该告诉您"赃物值",因此如果您在控制台中编写除"Nicu"(我的一个朋友的名字)之外的任何内容,该程序将显示"赃物级别超过 9000"。如果你写"Nicu",虽然它会说"对不起,在数据库中找不到赃物"。我的问题是,当我写"Nicu"时,如何让程序给我这个答案?以下是我对该程序的看法:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
char b,a;
a='Nicu';
cout<<"Insert your name: ";
cin>>b;
if (b==a){
cout<<"Sorry ! Couldn't find swag in database... "<<endl;
}
else if (b!=a){
cout<<"Swag level over 9000 "<<endl;
}
system ("PAUSE");
return 0;
}
这是它给我的错误:[错误]Id 返回了 1 个退出状态,它突出显示了代码的a='Nicu'
部分。即使我在此代码中使用了char
,我仍然不知道它的作用,但至少我确定int
不能与字母一起使用。
char
用于存储单个字符。
可以使用std::string
来存储字符串。
重写
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string a = "Nicu";
string b;
cout<<"Insert your name: ";
cin>>b;
if (b==a){
cout<<"Sorry ! Couldn't find swag in database... "<<endl;
}
else if (b!=a){
cout<<"Swag level over 9000 "<<endl;
}
system ("PAUSE");
return 0;
}
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
string b, a;
a = "Nicu";
cout<<"Insert your name: ";
cin>>b;
if (b==a){
cout<<"Sorry ! Couldn't find swag in database... "<<endl;
}
else if (b!=a){
cout<<"Swag level over 9000 "<<endl;
}
system ("PAUSE");
return 0;
}
为什么
不使用字符串而不是字符?对于比较字符串,您应该使用"strcomp"
#include <stdio.h>
#include <string.h>
int main()
{
string other;
string that;
if(strcmp(other, "hi")) // comparing the characters in this string with the text possibility "hi."
{
// do whatever you want if they are equal.
}
//Or.
if(strcmp(other, that)) // comparing both strings rather than a string with a possibly extracted text to compare it with alongside another string comparing both strings at once.
{
// do whatever you want if they are equal.
}
}
相关文章:
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- std::vector的包装器,使数组的结构看起来像结构的数组
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 找到两对数字,使它们的乘积的绝对差最小化
- C++:如何使函数只返回作为列表一部分的字符串
- Python中的for循环与C++有何不同
- c++使用foreach使数组为null
- 使外部项目可用于find_package CMake
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 是否可以在C++中使变量真正只读
- 有可能使shared_ptr协变吗
- 使lambda不可复制/不可移动
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 如何使用OpenMP使这个循环并行
- 根据变量使Qt UI中的复选框为已选中/未选中
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- 通过交换元素使数组相同
- C++11编译器何时会使RVO和NRVO优于移动语义和常量引用绑定