cout Issues

Hello,
I am reading the following data:
Johnson 5000
Miller 4000
Duffy 6000
Robinson 2500
Ashtony 1800

I would like the name, number of votes and percentage in 3 columns on the same line.
i.e
Johnson 5000 25.9%

I moved things around but nothing seems to work. Please help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main()
{
	string filename = string();
	string name[] = { " " };
	double votes[] = { 0 };
	double percent[] = { 0 };
	int i = 0;
	double sumVotes = double();


	cout << "Please enter the name of the file with.txt: ";
	cin >> filename;

	ifstream in;
	in.open(filename);


	while (!in.eof())
	{
		in >> name[i] >> votes[i];
		cout << name[i] << " " << votes[i] << endl;
		++i;
		
	}

	

	for (i = 0; i < 5; i++)
	{
		sumVotes = sumVotes + votes[i];
	}
		
		cout << "Total " << sumVotes << endl;

		
	for (i = 0; i < 5; i++)
	{
		percent[i] = (votes[i] / sumVotes) * 100;
		cout << percent[i] << endl;
	}

}
First I suggest you review how to declare variables in C++, you seem to have some misunderstanding of the process.
http://www.cplusplus.com/doc/tutorial/variables/

Second you should be supplying compile time constant sizes for your arrays, or better yet start using std::vector instead.

Third you should always check if your file opened properly. The way your program is currently structured if the file fails to open you'll go into an infinite loop in your file reading loop. And since you're using arrays you should also always check that the array index doesn't go out of bounds for your array size.





Topic archived. No new replies allowed.