0
データファイルからの地区投票の結果と内訳を示すテキストファイル出力を作成しようとしています。私は計算するのに適切な数字を得ることに問題があります。投票文書(votes.dat)には、 "District and Y/N"という行に2文字しか含まれていません。なぜ私はエントリがほんの一握り(10未満)のときに4317448と2600960のような数字が出てくるのか分かりません。C++ outfileで数値を計算すると問題が発生する
#include <string>
string using namespace std
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
char vote;
int district;
int overallTotal;
int yesTotal;
int noTotal;
int d1Yesvotes;
int d1Novotes;
int d2Yesvotes;
int d2Novotes;
int d3Yesvotes;
int d3Novotes;
//open file
infile.open("votes.dat");
infile>>district>>vote;
//if statement for 'yes' and 'no' votes, containing nested if statements
if (district=='1')
{
if(vote=='Y')
{
yesTotal+1;
d1Yesvotes+1;
overallTotal+1; }
else if(vote=='N')
{
noTotal+1;
d1Novotes+1;
overallTotal+1; }
}
else
if (district=='2')
{
if(vote=='Y')
{yesTotal+1;
d2Yesvotes+1;
overallTotal+1;}
else if(vote=='N')
{ noTotal+1;
d2Novotes+1;
overallTotal+1;}
}
else
if (district=='3')
{
if(vote=='Y')
{yesTotal+1;
d3Yesvotes+1;
overallTotal+1;}
else if(vote=='N')
{ noTotal+1;
d3Novotes+1;
overallTotal+1;}
}
outfile.open("votingresults.txt");
outfile<<endl<<"Number of Overall votes: "<<overallTotal;
outfile<<endl;
outfile<<endl<<"Number of Yes votes: "<<yesTotal;
outfile<<endl<<"Number of No votes: "<<noTotal;
outfile<<endl;
outfile<<endl<<"Number of District 1 Yes Votes: "<<d1Yesvotes;
outfile<<endl<<"Number of District 1 No Votes: "<<d1Yesvotes;
outfile<<endl;
outfile<<endl<<"Number of District 2 Yes Votes: "<<d1Yesvotes;
outfile<<endl<<"Number of District 2 No Votes: "<<d1Yesvotes;
outfile<<endl;
outfile<<endl<<"Number of District 3 Yes Votes: "<<d1Yesvotes;
outfile<<endl<<"Number of District 3 No Votes: "<<d1Yesvotes;
//close files
infile.close();
outfile.close();
return 0;
}
マイナーな改善:リファクタリングによってコードの半分を節約することができます。 (投票== 'Y'){yestotal ++、overalltotal ++ if(district == '1')D1Yesvotes ++ .... – xyious
これは私がatmを持っているものです:https://pastebin.com/w8Pu7tFD まだ出力されていません適切なテキストファイル。すべてがまだvotingresults.txt –
にゼロとして表示されています。問題は私のデータファイルに地区と投票の間にスペースがあることでした。ハハ。お手伝いありがとう! –