2016-11-30 102 views
0

输入20个单词,然后输出单词并计算每个单词输入的次数。字数组输入和输出并计算输入量

例如,如果我输入苹果5倍和香蕉3次,一些换句话说所以它增加了UPP〜20它应该输出:苹果= 5香蕉= 3猕猴桃= 1个橙= 1等。

#include <iostream> 
#include <windows.h> 
#include <string> 
using namespace std; 
int main() 
{ 
    string ord[21]; 
    for(int i=1; i<21; i++) 
    { 
     system("CLS"); 
     cout<<"Enter word number ["<<i<<"] :"; 
     cin>>ord[i]; 

    } 
    for(int i=1; i<21; i++) 
    { 
     int count=1; 
     for(int x=i+1; x<21; x++) 
     { 
      if(ord[x]==ord[i]) 
      { 
      count++; 
      } 
     } 
     cout<<ord[i]<<"="<<count<<endl; 
    } 
} 

这是我的代码到目前为止它在某种程度上的作品,但如果你运行它,你可以看到它说一个单词已被重复,然后它再次显示该单词,但这次它说它已被重复少一次。

+0

为此,我推荐一个[无序映射](http://en.cppreference.com/w/cpp/container/unordered_map),其中字符串作为键,计数作为数据。 –

+0

至于你对当前代码的问题,请学习如何使用调试器。有了它,您可以逐行浏览代码,同时观察变量及其值。通过这样做你的问题应该变得明显。 –

回答

0

让美国RUN通过代码

对于这个例子的目的,让我们5个字,而不是20

可以推断它20后

我的5项是

apple

apple

香蕉

猕猴桃

香蕉

所以第一个for循环(具有i)将苹果作为ORD开始[I]

它进入第二个for循环(x)的

X从第二字

第二字-no匹配计数变为2

开始

3ND字-no匹配计数保持-no匹配计数保持2

4ND字2

5ND字-no匹配计数保持2

因此第一环路(ⅰ)输出是2对苹果

现在for循环(i)的第二乐趣ORD又是苹果! 从x 3开始,因为i是2并且x = i + 1的 所以订... [X]是 香蕉猕猴桃 香蕉 这意味着

3ND字-no匹配计数保持1个

4ND字 - 没有匹配计数停留1

5ND字 - 没有匹配计数停留1

因此输出为1苹果再次

有通过u得到单词的重复和数量不当的话

渡过这个初始化count=0 ,让X从1开始以及x=1x=i+1 这将让你正确的数字

0
#include <iostream> 
#include <windows.h> 
#include <string> 

using namespace std; 

int main() { 

    struct Word { 
     string word; 
     int count; 
    }; 

    Word words[21] = {}; 
    int distinctWordCount = 0; 
    string tempWord; 
    for (int inputWordCount = 1; inputWordCount < 21; inputWordCount++) { 
     system("CLS"); 
     cout << "Enter word number [" << inputWordCount << "] :"; 
     cin >> tempWord; 
     int count = 0; 
     for (; count < distinctWordCount; ++count) { 
      if (words[count].word == tempWord) { 
       words[count].count++; 
       break; 
      } 
     } 
     if (count == distinctWordCount) { 
      words[count].word = tempWord; 
      words[count].count++; 
      ++distinctWordCount; 
     } 
    } 

    for (int count = 0; count < distinctWordCount; ++count) { 
     cout << words[count].word << "=" << words[count].count << endl; 
    } 
} 
+0

你可以使用上面的代码而不是你提到的 –