我如何让这个程序读取这个人键入的字符串,看看字符串是否相等
How do I get the this program to read what the person type as a string and see if the strings are equal?
我需要帮助...如何让此程序读取此人键入的字符串并查看字符串是否相等?
#include <iostream>
using namespace std;
int main()
{
char name;
cout << "Type my name is:";
cin >> name;
if
name ==char('Mike') //this is where i think the problem is...
cout << "congrats";
else
cout << "Try again";
}
#include <iostream>
int main()
{
std::string name;
std::cout << "Type my name is:";
std::cin >> name;
if (name == "Mike") // Compare directly to the string "Mike"...
std::cout << "congrats";
else
std::cout << "Try again";
}
我认为使用std::
而不是using namespace std
总是更好的习惯。
你试过在 c++ 中使用 std::string 吗?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Type my name is:";
cin >> name;
if (name == "Mike"))
cout << "congrats";
else
cout << "Try again";
}
你的问题是char
是一个字符变量,而不是一个字符数组。如果要创建"c-string"(字符集合),请使用 char name[20]
。要创建字符串对象,请使用 string name
。不要忘记#include <string>
.下面是字符串的简短教程:http://www.cplusplus.com/doc/tutorial/ntcs/
如果要使用 c 字符串,则必须使用 strcmp(name,"Mike")
来比较两个字符串。如果两个字符串不同,则返回 true,因此要小心。
#include <iostream>
using namespace std;
int main()
{
char name[20];
cout << "Type my name is:";
cin >> name;
if (!strcmp(name,"Mike")) //C string equality tester
cout << "congrats";
else
cout << "Try again";
}
字符串更易于使用,因为您可以只使用相等运算符 ==
。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Type my name is:";
cin >> name;
if (name == "Mike") //Tests for equality using strings
cout << "congrats";
else
cout << "Try again";
}
另外,请注意引号。单引号('a'
)用于字符,双引号("Mike"
)用于字符数组(单词,句子等)。
char
是一个字符,请将所有char
替换为std::string
,并将#include <string>
添加到代码的开头。 std::string
将保存任意长度的字符串。
if
后跟大括号:if(...)
。在您的情况下if(name == char('Mike'))
或根据上面的建议if(name == std::string('Mike'))
.
在 C 和 C++ 中,两个引号'
和"
是不同的。'
用于单个字符,"
用于字符串。所以它需要if(name == std::string("Mike"))
.
你也可以写if(name == "Mike")
.
此外,您还应该制作括号以提高可读性并避免错误。if(...)
后,您通常会使用 {}
来封装在满足 if(...)
中的条件时要执行的指令。您的情况很特殊,因为括号可能会被省略为单个说明。
if(...)
{
...
}
else
{
...
}
int main()
{
string name;
string myname("Mike");
cout << "Type my name is:";
cin >> name;
if(name ==myname) //this is where i think the problem is...
{
cout << "congrats";
}
else
cout << "Try again";
}
这应该可以做到。但我相信你不想只硬编码"迈克"。一个很好的改进是从文件中获取名称,然后进行比较。还要记住,字符串 == 运算符区分大小写,因此 "Mike" != "mike"
- C++-字符串是否包含一个带有简单循环的单词
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 检查字符串是否"null" C++
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 检查字符串是否为整数
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何检查字符串是否正确以将其转换为 int?
- 程序检查字符串是否只包含 1 和 0?
- 检查字符串是否是拉平德罗姆
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- gtest:检查字符串是否等于两个字符串之一
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如何检查字符串是否以C++中的"ed"结尾;
- 字符串是否在其构造函数中复制数据
- 检查字符串是否是数字,然后将该数字转换为 int?
- 如何检查一个字符串是否包含多个其他字符串?
- 检查字符串是否仅包含字母
- 如何根据一个特定字母的出现来确定两个字符串是否相等?
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法