Another .csv question

I want to read a .csv file with two columns into two variables. The variables will then be used a couple of calculations, after which a value will be writen into a third column.

Example of the .csv:
1
2
1325.234,0
1233.234,10


I have the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
    using namespace std;

    ifstream inf("route.csv");

    if (!inf)
    {
        cerr << "error" << endl;
        exit(1);
    }

    while (inf)
    {
        std::string strInput;
        getline(inf, strInput, ',');
    }

	return 0;
}
If you want to use std::getline() then remember that the first column ends with a comma ',' but the second column does not, it ends with a line end.

Also do you want to read these as strings or numbers? The data looks a bit like its a float and an integer. If that is the case you might want to use >>.

http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <iostream>

int main()
{
	std::ifstream ifs("route.csv");

	float f; // first column
	int i; // second column
	char c; // to read the comma

	// put the reads in the while condition if possible
	while(ifs >> f >> c >> i)
	{
		// that way you know the read was a success
		// if you end up here
		std::cout << "f: " << f << std::endl;
		std::cout << "i: " << i << std::endl;
	}
}


Thanks Galik, I'll give it a go.
Topic archived. No new replies allowed.