2013-05-07 61 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