2. 编程统计候选人的得票数。设有3个候选人zhang、li、wang(候选人姓名不区分大小写),10个选民,选民每次输入一个候选人的名字,若选民输错候选人的姓名,则按废票处理。选民投票结束后,程序自动显示各候选人的得票结果和废票数,要求利用结构体数组表示3个候选人的姓名和得票结果,将最终的统计结果显示输出并写入文本文件中。
时间: 2024-02-06 12:10:16 浏览: 196
下面是一个示例代码,实现了统计候选人得票数的功能:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Candidate {
string name;
int votes;
};
int main() {
Candidate candidates[3] = { {"zhang", 0}, {"li", 0}, {"wang", 0} };
int invalidVotes = 0;
for (int i = 0; i < 10; i++) {
string candidateName;
cout << "Please enter the name of the candidate voted by the voter " << i + 1 << ": ";
cin >> candidateName;
bool validVote = false;
for (int j = 0; j < 3; j++) {
if (candidateName == candidates[j].name) {
candidates[j].votes++;
validVote = true;
break;
}
}
if (!validVote) {
invalidVotes++;
}
}
cout << "The results of the vote are as follows:" << endl;
for (int i = 0; i < 3; i++) {
cout << candidates[i].name << ": " << candidates[i].votes << " votes" << endl;
}
cout << "Invalid votes: " << invalidVotes << endl;
// write the result to a file
ofstream outFile("vote_result.txt");
if (outFile.is_open()) {
for (int i = 0; i < 3; i++) {
outFile << candidates[i].name << ": " << candidates[i].votes << " votes" << endl;
}
outFile << "Invalid votes: " << invalidVotes << endl;
outFile.close();
} else {
cout << "Failed to write to file." << endl;
}
return 0;
}
程序首先定义了一个结构体数组 candidates
,其中存储了三个候选人的姓名和得票数。然后通过循环让每个选民输入他/她所投票的候选人的名字,根据输入的姓名更新候选人的得票数。如果输入的候选人姓名无效,则废票数加一。最后程序输出各候选人的得票结果和废票数,并将结果写入到一个名为 vote_result.txt
的文本文件中。
注意,在实际应用中,可能需要对输入的候选人姓名进行一些格式化处理,比如转换为小写字母以避免大小写不一致的问题。
相关推荐










