Help1

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");


}

Didn't help...
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
You might be able to use setw

http://www.cplusplus.com/reference/iomanip/setw/
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.
Chervil,
That did the trick! Thank you, now why would counter work and not just x?
Last edited on
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.
Chervil,
Again thank you...
Topic archived. No new replies allowed.