请各位帮忙检查这段C++作业代码。
本帖最后由 肚子饿了233 于 2021-3-23 13:20 编辑#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;
int len = sizeof(words) / sizeof(words);
input(words, len);
order(words, len);
}
void input(struct WORD words[], int len)
{
int i;
cout << "输入几个英语单词:";
for (i = 0; i < len; i++)
{
cin >> words.word;
if (words.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.word.compare(words.word) > 0)
{
temp = words.word;
words.word = words.word;
words.word = temp;
}
else if (words.word.compare(words.word) == 0)
words.count++;
}
}
for (i = 0; i < len; i++)
{
cout << words.word << " : " << words.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.word == words.word)
{
words.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;
}
yuxijian2020 发表于 2021-3-25 16:47
一言难尽,我相当于重写了,你参考下吧...
谢谢你,但我还是C++小白,还没学vector容器,没太看懂,但还是谢谢你啦~
页:
[1]