0
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;
       }
   }
 }

これは、2 つの char 配列を比較し、文字が互いに対応する場合は 0 を返し、string1 の最初の文字が string2 の最初の文字より大きい場合は 1 を返し、string1 の最初の文字が の最初の文字より小さい場合は -1 を返す関数です。 string2.問題は、実行すると、2つの単語が異なっていても、出力が常に0で、「単語は同じです」というテキストが表示されることです。メイン プログラムで 2 つの配列を正しく初期化していますか?それとも他の問題がありますか?

4

2 に答える 2

2

この宣言

char word1[]={0};

サイズ 1 の配列を宣言します。つまり、入力を行うと、スタックが上書きされます。他のすべてのアレイについても同じです。

C++ で文字列を扱う場合は、std::string!を使用することを強くお勧めします。

于 2012-10-08T07:02:28.100 に答える
2
char word1[]={0};

この行は、0 に設定された要素を 1 つだけ持つ配列を作成します。この配列を使用して文字列を保持する場合、空の文字列以外は何もword1保持できません。空でない文字列をこの配列に読み込んで、この配列に割り当てられていないメモリの他の部分に書き込むため、ここでバッファオーバーフローが発生しています。これは非常に悪いです。

std::string代わりに文字列を保持するために使用することを検討してください。必要に応じて、割り当てのサイズが自動的に変更されます。

于 2012-10-08T07:03:25.360 に答える