int main()
{
cout<<"Enter a word"<<endl;
char word1[]={0}; //first char array initialization
cin>>word1;
cout<<"Enter another word"<<endl;
char word2[]={0}; //second char array initialization
cin>>word2;
char word3[]={0};
char word4[]={0};
int i=0;
while (word1[i]!='\0') //this converts both words to lower case by usinction tolower
{
word3[i]=char(tolower(word1[i])); //word3 and word4 stores the new arrays
word4[i]=char(tolower(word2[i]));
i++;
}
int output; //output stores the value of 0,1 or -1
output=compareString(word3,word4);
if (output==0)
{
cout<<"The two words are the same."<<endl; //if arrays are same
}
if (output==1)
{
cout<<"the 1st character of 1st word has a larger value than of 2nd word."<<endl;
}
if (output==-1)
{
cout<<"the 1st character of 2nd word has a larger value than of 1st word."<<endl;
}
return 0;
}
int compareString(char string1,char string2)
{
int size1=0; //initialize size of string1
int j=0; //string1 position initialize
while (string1[j]!='\0') //loop to determine size of string1
{
size1+=1;
j+=1;
}
int a=0; //initialize size of string2
int size2=0; //string2 position
while (string2[a]!='\0') //loop determines size of string2
{
size2+=1;
a+=1;
}
int i=0;
int k=0;
for (i=0;i<size1;i++) //loop to compare the two strings
{
if (string1[i]!=string2[i])
{
if (string1[i]>string2[i]) //comparing 1st character of string1 & string2
{
return 1;
}
else //if string2's first character is greater in value
{
return -1;
}
}
else
{
k++; //incrementing k when character of string1 matches string2 character
}
}
if (k==size1) //to cjheck if all characters of both strings are same
{
if (k==size2)
{
return 0;
}
}
}
这是一个比较两个char数组的函数,如果字符彼此对应则返回0,如果string1的第一个字符大于string2的第一个字符,则返回1,如果string1的第一个字符小于,则返回-1 string2的第一个字符。问题是当我运行它时,即使两个单词不同,输出也总是0,并出现文本“单词是相同的”。 我在主程序中正确初始化了两个数组吗?还是有其他问题?
答案 0 :(得分:2)
此声明
char word1[]={0};
声明一个大小为1的数组,这意味着当您执行输入时,它将覆盖堆栈。所有其他阵列都是一样的。
在C ++中处理字符串时,强烈建议使用std::string
!
答案 1 :(得分:2)
char word1[]={0};
这一行创建一个数组word1
,它只有一个元素,设置为0.当使用此数组来保存字符串时,除了空字符串外,你不能在其中包含任何。这里导致缓冲区溢出,因为您在此数组中读取了非空字符串,然后将其写入未分配给此数组的内存的其他部分。这非常糟糕。
请考虑使用std::string
来保存字符串。它会根据需要自动调整其分配大小。