2013-05-07 60 views
0

如果有人可以提供比我的更好的代碼,儘管工作也很糟糕,那將會很棒。此外,我的代碼有問題!當我打印我的新數組arr時,在輸出中,當存在重複單詞時,數組的位置會被跳過,並且會爲此輸出一個空白空間。從輸入中讀取單詞序列。使用「退出」來終止,按順序打印並不打印兩次。

例如:

bat, 
cat, 
mat, 
     //here the word bat is not printed again, but instead i get an empty space 
rat, 
quit, 

也請只使用指針,數組和字符串,因爲我還沒有研究載體,列表,地圖和這樣的。謝謝。

#include<iostream> 
#include<conio.h> 
#include<string> 

using namespace std; 

int main() 
{ 
    string word[100]; 
    string arr[100]; 
    int i=0,j,k,m,n; 

    while(1) 
    { 
     cout<<"enter word: \n"; 
     cin>>word[i]; 
     if(word[i]=="quit") 
     break; 
     i++; 
    } 

    for(j=i,m=0;j>=0,m<=i;m++) 
    {      
     for(k=j-1;k>=0;k--) 
     { 
      if(word[j] == word[k]) 
      goto start;       
     } 

     arr[m]=word[j];                
     start: 
     j--;          
    }             

    for(n=m;n>0;n--) 
     cout<<arr[n]<<"\n";           

    getch(); 
} 
+2

對[codereview.se]這可能會更好。 – 2013-05-07 09:15:16

+1

另外,歡迎來到Stack Overflow。請花時間閱讀 [faq]。你會得到一個[徽章](http://stackoverflow.com/badges)(c: – 2013-05-07 09:16:08

+2

@PeterWood:代碼審查是代碼_works_。 – Mat 2013-05-07 09:17:11

回答

0

固定了一下,我並沒有想花時間去了解你的for(j=i,m=0;j>=0,m<=i;m++)週期等方面充分rewrited它。

#include<iostream> 
#include<conio.h> 
#include<string> 

using namespace std; 

int main() 
{ 
    string word[100]; 
    string arr[100]; 
    int wordCount = 0; 

    while(1) 
    { 
     cout<<"enter word: \n"; 
     cin>>word[wordCount]; 
     if(word[wordCount] == "quit") 
     { 
      break; 
     } 
     ++wordCount; 
    } 

    int arrCount = 0; 
    for(int i = 0; i < wordCount; ++i) 
    {     
     bool found = false; 
     for (int j = 0; j < arrCount; ++j) 
     { 
      if (arr[j] == word[i]) 
      { 
       found = true; 
       break; 
      } 
     } 
     if (!found) 
     { 
      arr[arrCount] = word; 
      ++arrCount; 
     } 
    }             

    for(int i = 0; i < arrCount; ++i) 
    { 
     cout<<arr[n]<<"\n"; 
    } 

    getch(); 
} 

而且從不使用goto,如果他看到你的teatcher會很生氣。

+1

IHMO在'found = true;'後面插入'break;'會更好;' – borisbn 2013-05-07 09:24:35

+0

@borisbn,是的,我的錯誤 – SpongeBobFan 2013-05-07 09:27:27

+0

ya,我knw goto sucks:P – aghoribaba 2013-05-07 09:28:42