using namespace std;
int WordsCount(string &pText);
int CountWordsInText(string &pFileName) {
ifstream ifile; string text; int words = 0;
ifile.open(pFileName.c_str()); if (ifile.is_open()) {
while (!ifile.eof()) {
getline(ifile, text);
words += WordsCount(text); } }
ifile.close(); return words; }
int WordsCount(string &pText) {
int words = 0;
string::size_type pos = 0;
pos = pText.find_first_of(' ', pos); while (pos != pText.npos) {
pos++; words++;
pos = pText.find_first_of(' ', pos); }
words++; return words; }
int main() {
string file = \"test.txt\";
cout<将要测试的文本文件放在工程目录下即可。不限定候选人的情况下,可以采用链表(或者类),这样可以随时增加候选人(或类对象)。选票就采用一维数组好了,这样线性时间就可以完成。查找时间O(n),排序可以用各种排序算法,如冒泡排序。
用c++编写的选票系统,并可统计相关得票情况-#include using namespace std struct Person//声明结构体类型Person; { char name[20] int count } int main() { Person
leader[3]={\"aaa\定义Person类型的数组,内容为当前候选人的姓名及得票数; char leader_name[20] //leader_name为投票人所选的人姓名; int i,j for(i=0 i<10 i++) { cin>>leader_name //先后输入十张票上所选的人的姓名; for(j=0 j<3 j++) { if(strcmp(leader_name,leader[j].name)==0) leader[j].count++ //所选人与候选人的姓名相同,则该候选人的票数加1; } } cout<1.问题描述设有n个候选人参加选举,统计每个人最后的得票情况。 2.基本要求
(1)以数组作为存储结构;
(2)设计统计得票算法,将最后的得票情况统计并输出。3
.设计思想:可以将每个候选人设计作为一个结构类型,包括名字和得票数,将n个候选人组成一个结构数
组,其存储结构定义如下:const int n=10;//假设有10个人参加选举struct Person{char *name;int count;}Leader[n];可以从键盘依次输入选举情况,每次输入一个人的名字,将输入的名字与结构数组Leader进行比较,将对应候选人的得票数增加1 【思考题】将该问题用C++中的类实现。。。。代码后面最好有解释。。。
个人建议既然你学C++就不要用char* 应该用string替换,以下是我刚才写的基于类的实现,我已经在VC6.0上测试过无误代码如下: #include #include using namespace std; typedef struct candidate {string name; //候选人名 int votecount; //选票 }stCand,*pstCand; class vote { private:
pstCand pcand; //候选人数组 int candnum; //总的候选人
int nowcandnum; //现在又几个候选人 public:
vote(int n = 0); ~vote();
void addVote(const string &st); void output(); };
vote::vote(int n) //n表示有多少个获选人 { if(n==0) {
candnum = 0; pcand = NULL; } else {
candnum = n;
pcand = new stCand[n]; }
nowcandnum = 0;
}
vote::~vote() {
delete [] pcand; pcand = NULL; }
void vote::output() //输出选举结果 当然如果需要可以在输出结果后进行排序 {
for (int i=0;icout<void vote::addVote(const string &st) {int flag = 0; //当前所存名单是否有该人
for(int i=0;iif(st == pcand[i].name) {flag = 1; //已经找到该人 break; } i++; }
if(flag == 1) {
pcand[i].votecount++; }
else if(i< candnum) //如果没有出现过 增加该人名 {
pcand[i].name = st; pcand[i].votecount=1; nowcandnum ++; }
else //候选人名单已经超过所要求的候选人个数 {
cout<<\"error! the candidate num is overflow!\"<int m = 0;cout<<\"please input the candidate num:\";
cin>>m; string stemp;
vote svote(m); //创建选举类
cout<<\"please input the candidate name,enter “q” or“ Q” to exit input!\"<cin>>stemp;if(stemp==\"Q\" || stemp == \"q\") {
cout << \"vote type-in is ending!\"<svote.addVote(stemp); }svote.output(); return 0; }