Content of .csv File to a Vector

Hi, first time poster here, I was hoping to get some help on a current assignment here. my c++ skills are rather rudimentary so I apologize in advance and I do hope this comes off as an appropriate question for this board.

My assignment is currently to display the contents of a .csv file into a vector, have the user input a number or string of characters into the console, and then the program will then tell the user if it found what was typed in.

The one question that I have is how exactly would I store the data from the .csv file into a vector? I don't have much experience with vectors so I would appreciate some input on how I would go about this. I looked through the forums for similar questions, some do deal with .csv files to vectors but what I would really like is a brief (thorough if time permits) explanation of what is required to make this happen.

My knowledge of c++ syntax is rather rough so layman's terms would be helpful.
Below is the current code I have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main()
{

	vector <string> myFile;

	string filename;
	ifstream file;
	cout << "Please enter the name of the file you are looking for." << endl;
	getline(cin, filename);
	file.open(filename.c_str());

	cout << endl;


	if (file.is_open())
	{
		cout << "The file is open" << endl;
		cout << "File contents: " << endl;
	}

	else
	{
		cout << "The file you enter can not be found." << endl;
	}

	system("pause");
	return 0;
}


Any feedback would be very much appreciated.
There are several ways to do that. The first I think of is to load the whole file into a std string and then use find() and substr to chop it based on cammas, push_back() that into your vector <std::string>....
If the teacher disallows std::string, then I'd set up a cstring called buffer that is some multiple of 8 (usually 1024). Loading from a file is slow, loading into a buffer in specific-sized chunks will speed things up. Then search for the csv pattern.

Hint; beware, you might have to ignore cammas between quotes and other pitfalls that the teacher has worked into the data.
Last edited on
Use getline to read a line into a string.
Create a stringstream from that string.
Use the delimited form of getline to read each field from the stringstream.
Thanks guys, I appreciate the help! My problem has been solved.
Topic archived. No new replies allowed.