How can i achieve this result?

Hello all, here's my code

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

int main()
{
	const int SIZE = 255;
	char filename[SIZE];
	char item[SIZE];
	ifstream inputFile;

	cout << "Enter the name of the file: " << endl;
	cin.getline(filename, SIZE);

	inputFile.open(filename);
	if (!inputFile)
	{
		cout << "Error reading file.\n";
		exit(0);
	}

	while (inputFile >> item)
	{
		cout << item << ",";
                //how can i make it skip to a new line after every 5 items have been displayed?
	}
	inputFile.close();
	return 0;
}


Ok so what i'm trying to do is i'm trying to display the items inside a file that the user input separated by comma. Every 5 items displayed, i want the program to jump to a new line. This sounds a lot like a for loop to me but i don't know how to do it.
Last edited on
Hi there,
the easiest way could be with a counter in your current code.
It can be done with a for loop too, but I don't see a real benefit to do so.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
...
int counter = 0; /* Define and initialize your counter */
while(inputFile >> item)
{
    cout << item;
     /*
      * Check if we incremented 4 times, because we print before we count
      * so there's always an additional element in front
      */
    if (counter == 4) 
    {
        cout << endl; /* Print end of line if we do  */
        counter = 0; /* Reset the counter */
     } else {
        cout << ","; /* Print a comma instead */
        counter++; /* Increment the counter */
     }
}
...
Last edited on
Thank you! :)
Topic archived. No new replies allowed.