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):
#include <iostream>
#include <fstream>
#include <string>
usingnamespace 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';
}
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 ^_^