Could not print out inside the for loop

I have coding that needs to print out the file and also find some value from the file. This is my coding :

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
string input;
fstream nameFile;
nameFile.open ("data.txt", ios :: in);

if (nameFile)
{
getline (nameFile, input);
while (nameFile)
{
cout << input << endl;
getline (nameFile, input);
}
}
else {
cout << " ERROR : cannot open file.\n "; }



int largest_1 {};
int largest_2 {};
int largest_3 {};

for (int a {}, b {}, c {}, d {}, e {}; nameFile >> a >> b >> c >> d >> e;)
{

if (c > largest_1 )
largest_1 = c;
if (d > largest_2 )
largest_2 = d;
else if (e > largest_3 )
largest_3 = e;

std::cout << "The largest value 1 is " << largest_1 << '\n';
std::cout << "The largest value 2 is " << largest_2 << '\n';
std::cout << "The largest value 3 is " << largest_3 << '\n';
}
}


However after i run this coding, it didn't print inside of the for loop. anyone know how to fix this ?
Once you have displayed the contents of the file, the file is not in a good state and it's get pointer is also not at the beginning - so you have to reset the status and move the pointer back to the beginning. Also the getline() is usually part of the while condition. Perhaps (not tried):

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

int main()
{
	string input;
	ifstream nameFile("data.txt");

	if (!nameFile)
		return (cout << " ERROR : cannot open file.\n"), 1;

	while (getline(nameFile, input))
			cout << input << endl;

	nameFile.clear();
	nameFile.seekg(0);

	int largest_1 {};
	int largest_2 {};
	int largest_3 {};

	for (int a {}, b {}, c {}, d {}, e {}; nameFile >> a >> b >> c >> d >> e; ) {
		if (c > largest_1)
			largest_1 = c;

		if (d > largest_2)
			largest_2 = d;

		if (e > largest_3)
			largest_3 = e;
	}

	std::cout << "The largest value 1 is " << largest_1 << '\n';
	std::cout << "The largest value 2 is " << largest_2 << '\n';
	std::cout << "The largest value 3 is " << largest_3 << '\n';
}

Last edited on
The for loop will not print because the previous while loop consumed all data.

So either you open the file a second time or you reset the read position using seekg() to the top, see:

http://www.cplusplus.com/reference/istream/istream/seekg/
Thank you so much @seeplus. I have run it and it works. Thank you very much. This is my project for my degree actually but this is just like 20% progress. Learning online is hard plus my lecturer won't answer my question regarding the project. You are my life saver now. Thank you ^_^

Thank you too @coder777
Topic archived. No new replies allowed.