Hello, I just learned c++. I have a data with 4 rows and 3 column
2019 2 15
2018 3 23
2017 4 09
I need to read this file by column. I know how to read it by rows but didn't really understand. I really appreciate it if you guys could help me. Thank you
What do you want to do with the column(s)? You only read the file line by line. Depending upon what you are trying to do, then depends upon how you process/store the read data.
#include <fstream>
#include <iostream>
int main()
{
std::ifstream ifs("data.txt");
if (!ifs)
return (std::cout << "Cannot open file\n"), 1;
int high {};
for (int a {}, b {}, c {}; ifs >> a >> b >> c;)
if (b > high)
high = b;
std::cout << "The highest column 2 value is " << high << '\n';
}
From the computer's perspective, there are no columns and there are no rows. There are just bytes. This is a little clearer if you write the file like this:
2019 2 15\n2018 3 23\n2017 4 09
Accordingly, a program just reads sequences of bytes. You can "seek" to a particular position in the file so that the next read will start from that position, but you can't seek to a particular column since the computer has no sense of columns.
This is a long-winded way of saying that you have to read your file from beginning to end and just ignore the parts that you don't want.
Yes - assuming that smallest is set to some initial high value that won't be encountered. Setting it to say 0 won't work - as 0 is likely to be less than the minimum value so the if condition would be false.