C++ 如何正确比较c++;?
大家晚安 <>我试图用C++来比较2个字符串,使用.COMPRACE()函数。然而,我看到的结果并不是这个函数所期望的结果。请看一看C++ 如何正确比较c++;?,c++,C++,大家晚安 我试图用C++来比较2个字符串,使用.COMPRACE()函数。然而,我看到的结果并不是这个函数所期望的结果。请看一看 #include <iostream> #include <string> using namespace std; class game { private: char mtx [2][2]; int i = 0, j = 0, a = 0; std::string matrix1; std
#include <iostream>
#include <string>
using namespace std;
class game
{
private:
char mtx [2][2];
int i = 0, j = 0, a = 0;
std::string matrix1;
std::string xis = "xx";
public:
game();
char winner();
};
game::game()
{
for(i = 0; i<2; i++)
{
for (j = 0; j<2; j++)
{
mtx [i][j] = 'x';
}
}
char game::winner()
{
i = j = 0;
for (j=0; j<2; j++)
{
matrix1 = mtx [0][j]; //string recieve the first line of the matrix.
}
a = xis.compare(matrix1);
cout << a<<endl;
}
int main(void) {
velha game;
velha.winner;
}
#包括
#包括
使用名称空间std;
班级游戏
{
私人:
char-mtx[2][2];
int i=0,j=0,a=0;
std::字符串矩阵1;
std::string xis=“xx”;
公众:
游戏();
char winner();
};
game::game()
{
对于(i=0;i#包括
#包括
内部主(空){
std::字符串第一,第二;
std::cout对于字符串比较
和甚至strcmp
返回的值将是两个字符串的字典比较。以下是您应该看到的值:
否定如果*此
按字典顺序显示在参数指定的字符序列之前
0如果*此
与指定的字符序列等效
正值如果*此
按字典顺序显示在参数指定的字符序列之后
如果要获取矩阵的第一列,请在上进行字符串比较,您可能希望执行以下操作:
for(int col = 0; col < 2; col++) {
matrix1.push_back(mtx[0][col]); // This appends that character to the end of your string
}
我已通过测试比较矩阵是否包含“xx”最后得到了0。然而,一个更容易的比较方法是使用operator==
简单地返回true
或false
值。您可以使用string1==string2
与字符串进行比较。这是通过运算符重载()提示:尽量避免使用名称空间std
,只保留前缀。这有助于避免与用户定义的类、结构和函数发生冲突。是的,如果他需要制作更大的程序,那么他们就需要。为了澄清,我提供了。不确定这一解释的含义。std::
前缀有助于学习,因为在哪里可以找到文档是显而易见的。一开始看起来很烦人,但你已经习惯了。一旦你习惯了,就更容易阅读,因为这些符号有助于更好地区分事物,特别是当你开始使用Boost和其他名称空间库时。
for(int col = 0; col < 2; col++) {
matrix1.push_back(mtx[0][col]); // This appends that character to the end of your string
}
matrix1 = mtx[0];
// To ensure you have a null terminated string
// Otherwise you will have garbage.
matrix1.replace(matrix1.begin() + 2, matrix1.end(), 1, "\0");