Read from file

I have a file saved in the csv format and I want to write a program that reads from that file. I want the program to read each character but when a comma is encoutered it saves all the characters before that.
Been doing some reading on string manipulation but nit been successful
any advise?

Do it in a 2 step process. Use getline() to read lines from the input. Then create a stringstream from each line and use getline() on the stringstream, but tell it that the delimiter is a comma.

IMPORTANT NOTE: This method assumes that you don't have quoted text containing commas in the stream. If that's a possibility then you need a different method (a state machine) which I can also describe.

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

using std::istringstream;
using std::cin;
using std::cout;
using std::flush;
using std::string;


int main()
{
    string line;
    while (getline(cin, line)) {  // read lines from the input
	cout << "line: " << line << '\n';
	istringstream ss(line);  // create a string stream from the line
	string field;		// a field in the csv
	while (getline(ss, field, ',')) {   // read comma-separated fields from the line.
	    cout << "\tfield: " << field << '\n';
	}
    }
}

Input:
Name,Age,Major
Dave,53,Electrical Engineering
Scottie,50, Psychology
Olivia,21,Molecular Biology

Output:
line: Name,Age,Major
        field: Name
        field: Age
        field: Major
line: Dave,53,Electrical Engineering
        field: Dave
        field: 53
        field: Electrical Engineering
line: Scottie,50, Psychology
        field: Scottie
        field: 50
        field:  Psychology
line: Olivia,21,Molecular Biology
        field: Olivia
        field: 21
        field: Molecular Biology
line:

Topic archived. No new replies allowed.