### 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.

 ``123456789101112131415161718192021222324252627`` ``````#include #include #include 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...
 ``12345`` ``````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.
 ``1234567891011`` `````` 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.