Read file by column

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.
for example the second column , between 2 , 3 and 4 , i need to find the highest value. Therefore i need to divide it by columns right ?
Well to just find the highest column 2 value:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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';
}



The highest column 2 value is 4

Last edited on
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.
alright, thank you so much. I really appreciate it
btw, if I want to find the smallest, can i just do

if ( b < smallest )
smallest = b;
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.

Topic archived. No new replies allowed.