看板 civil92 關於我們 聯絡資訊
#include<iostream> // 從螢幕 input or output #include<fstream> //因為要從檔案抓、寫資料 #include<string> //用到字串 #include<vector> //用到向量 using namespace std; void get_names(vector<string> & names); void print_summary(const vector<string> & name,const vector<int> & count); void initialize(vector <int> & count); void tally(vector <int> & count); int main() { vector <string> cand_names(5); vector <int> vote_counts(5); get_names(cand_names); initialize(vote_counts);//歸零 tally(vote_counts); print_summary(cand_names,vote_counts); return 0; } void get_names(vector<string> & names) { ifstream names_in; int cand; names_in.open("candnames.txt"); for (cand=1;cand<=4;cand++) names_in>>names[cand]; names_in.close(); } void print_summary(const vector<string> & name,const vector<int> & count) { int cand; for (cand=1;cand<=4;cand++) cout << name[cand]<<" : "<< count[cand]<<endl; } void initialize(vector <int> & count) { int cand; for (cand=1;cand<=4;cand++) count[cand]=0; } void tally(vector <int> & count) { int cand; ifstream vote_in; vote_in.open("votes.txt"); while(vote_in>>ws &&!vote_in.eof()) { vote_in >> cand; if(cand>=1 && cand<=4) count[cand]++; else cout <<"invalid vote: "<< cand << endl; } vote_in.close(); } // 要在 .cpp 同一目錄做 candnames.txt 和 votes.txt 兩個檔 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.7.59