|  | 
 
| 
本帖最后由 肚子饿了233 于 2021-3-23 13:20 编辑
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  
 #include<iostream>
 #include<string>
 void input(struct WORD words[], int len);
 void order(struct WORD words[], int len);
 using namespace std;
 struct WORD
 {
 string word;
 int count = 1;
 };
 int main()
 {
 struct WORD words[10];
 int len = sizeof(words) / sizeof(words[0]);
 input(words, len);
 order(words, len);
 }
 void input(struct WORD words[], int len)
 {
 int i;
 cout << "输入几个英语单词:";
 for (i = 0; i < len; i++)
 {
 cin >> words[i].word;
 if (words[i].word == "0") break;
 }
 }
 void order(struct WORD words[], int len)
 {
 int i, j;
 string temp;
 for (i = 0; i < len; i++)
 {
 for (j = i+1; j < len; j++)
 {
 if (words[i].word.compare(words[j].word) > 0)
 {
 temp = words[i].word;
 words[i].word = words[j].word;
 words[j].word = temp;
 }
 else if (words[i].word.compare(words[j].word) == 0)
 words[i].count++;
 }
 }
 for (i = 0; i < len; i++)
 {
 cout << words[i].word << " : " << words[i].count << endl;
 }
 }
 
 编写一程序(应该有多个函数),允许从键盘输入任意多个英语单词(单词可以重复),中间用空格分开,输入0表示输入结束。该程序可以统计同一个英语单词被输入几次,最后对英文单词按字典顺序输出,后面跟上该单词被输入的次数。(提示,尝试用结构体组织数据,把单词和该单出现的次数用一个结构体来描述。
 
 
 编译结果:输入几个英语单词:can
 ban
 app
 app
 0
 : 6
 : 5
 : 4
 : 3
 : 2
 0 : 2
 app : 2
 app : 1    //这一行也想删掉,怎么修改?
 ban : 1
 can : 1
 
 
 :6,  :5.......这些是什么玩意儿?!怎么删掉?
 请大佬们指出我的错误吧!救救菜鸟5555
 
 
 
 
一言难尽,我相当于重写了,你参考下吧... 复制代码#include<iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct WORD
{
    string word;
    int count = 1;
    bool operator()(const WORD& a, const WORD& b)
    {
        return a.word < b.word;
    }
};
void input(vector<WORD>& words)
{
    char c;
    string temp;
    WORD tWord;
    cout << "输入几个英语单词:";
    //从这里开始就不对,不要用cin....
    //题目上说单词中间是空格隔开
    //不是回车区分单词
    while (c = getchar())
    {
        if ((c >= 'A' && c <= 'Z') || c >= 'a' && c <= 'z')
            temp.append(1, c);
        else if (c == ' ' || c == '0')
        {
            tWord.word.assign(temp);
            words.push_back(tWord);
            temp = "";
            if (c == '0')
                break;
        }
    }
}
void order(vector<WORD>& words)
{
    //去重
    for (int i = 0; i < words.size() - 1; ++i)
    {
        for (int j = i + 1; j < words.size(); ++j)
        {
            if (words[i].word == words[j].word)
            {
                words[i].count += 1;
                words.erase(words.begin() + j);
                j -= 1;
            }
        }
    }
    //排序
    sort(words.begin(), words.begin() + words.size(), WORD());
}
void VectorPrint(const vector<WORD>& words)
{
    for (const auto& item : words)
    {
        printf_s("%s : %d\n", item.word.c_str(), item.count);
    }
}
int main()
{
    vector<WORD> words;
    input(words);
    order(words);
    VectorPrint(words);
    return 0;
}
 | 
 |