2012-10-08 22 views
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; 
     } 
    } 
} 

這是比較兩個字符數組,並返回0,如果字符對應於彼此的函數,如果字符串2的第一個字符是比值,並返回字符串2的第一個字符,則返回1如果string1的第一個字符小於string2的第一個字符,則爲-1。問題是,當我運行它時,即使兩個單詞不同,輸出始終爲0,並且文本「單詞相同」出現。 我是否在我的主程序中正確初始化了兩個數組?或者是否存在其他一些問題?

+1

爲什麼你沒有給出char數組的大小? – goji

+0

你的數組是一個元素。如果可以的話,使用'std :: string'。不是爲了殺死函數的這一點,而是它有一個「比較」函數,它可以像==和>這樣的特定運算符。 – chris

+0

@Troy,如果您提供了初始化程序列表,它會推導出大小。 – chris

回答

2

這個聲明

char word1[]={0}; 

聲明大小爲1的數組,這意味着當你做你的輸入,它將覆蓋堆棧。對於所有其他陣列也是如此。

在處理C++中的字符串時,強烈建議使用std::string

+0

如何初始化用戶確定數組大小的數組? – User14229754

+0

我的意思是對於字符串'std :: string',沒有固定大小 – User14229754

+0

@ user1692446。用於其他數據'std :: vector'。 –

2
char word1[]={0}; 

該行創建恰好具有一個元素,被設置爲0。當使用這個數組來保存一個字符串數組word1,你不能抱任何這只是一個空字符串。你在這裏引起了一個緩衝區溢出,因爲你在這個數組中讀入了一個非空字符串,然後它會寫入其他未分配給這個數組的內存部分。這真是太糟了。

請考慮使用std::string來保存字符串。它會根據需要自動調整其分配。

+0

我必須根據我的任務使用字符數組。 – User14229754

+0

然後讓它們變得非常大,每個都有1024個元素。比任何通常會輸入到程序中的字符串更大。 – cdhowie