Help1

Apr 21, 2014 at 12:42am
How can I display my eight numbers in three columns?
12
13
15
17
18
15
18
19

I get them to display correctly I just can't seem to get them in three columns
I was thinking if ((x + 1) % 3 == 0) but it doesn't work.

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
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main()
{
	ifstream fin;
	fin.open("data.txt");
	int x = 0;
	int counter = 0;

	while (fin >> x)
	{
		
		cout << x <<"\t";
		counter = counter += 1;

	}
	
	cout << "Total numbers:" << counter << endl;
	system("pause");


}

Apr 21, 2014 at 1:12am
Apr 21, 2014 at 1:16am
Didn't help...
Apr 21, 2014 at 1:20am
Using your idea:
1
2
3
4
5
cout << counter;
if ((counter + 1) % 3 == 0)
    cout << '\n';
else
    cout << ' '; // I don't like using tabs to align things 

Edit: oops
Last edited on Apr 21, 2014 at 1:52am
Apr 21, 2014 at 1:24am
You might be able to use setw

http://www.cplusplus.com/reference/iomanip/setw/
Apr 21, 2014 at 1:50am
Test the counter, not x.
1
2
3
4
5
6
7
8
9
10
11
    int x = 0;
    int counter = 0;

    while (fin >> x)
    {
        if ((counter>0) && (counter%3==0))
            cout << endl;
        cout << setw(3) << x;
        counter++;
    }
    cout << endl;

The test of (counter>0) is simply to avoid a blank line at the start, but you might omit this if you like.
Apr 22, 2014 at 7:53pm
Chervil,
That did the trick! Thank you, now why would counter work and not just x?
Last edited on Apr 22, 2014 at 7:56pm
Apr 22, 2014 at 10:39pm
why would counter work and not just x?

Well, counter behaves in a predictable and known way, whereas the values of x are all over the place. More relevantly, in order to arrange the numbers into three columns, you need some way of counting how many values have been printed in a column, and the counter fulfils exactly that requirement.
Apr 22, 2014 at 11:04pm
Chervil,
Again thank you...
Topic archived. No new replies allowed.