Convert string into array of char, CSV file

Ok so I'm reading from a CSV file and I have been reading the data with the getline function, I've converted the first three "strings" into integers which are person.year, person.month, and person.day. Now I need to convert a string into an array of characters for person.name but don't know how to do so.

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
35
36
37
38
39
40
41
  bool displayLogFile_CSV(fstream &file)
{
	WaterLog person; // one data record
	string sectorlog; //holds string for sector
	string input; //holds input of file as string

	if (!file)
		return false;
	else
	{
		

		//display report header
		cout << "NAME" << setw(20) << "ID" << setw(15) << "DATE"
			<< setw(15) << "SECTOR"
			<< setw(15) << "MONTH_1" << setw(15) << "MONTH_2"<< setw(15) << "MONTH_3"
			<< setw(15) << "TOTAL" << setw(15) << "AVERAGE" << endl;

		

		//white getline function moves to next line, read and display each record
		while (getline(file, input))
		{
			getline(file, input, '\n'); //ignores the header of file

			getline(file, input, ',');
			person.year = atoi(input.c_str());

			getline(file, input, ',');
			person.month = atoi(input.c_str());

			getline(file, input, ',');
			person.day = atoi(input.c_str());

			getline(file, input, ',');
			// I need to convert the string into an array of characters here for person.name
			
		}
	}
	return true;
}
Last edited on
strcpy(target,string.c_str());

or, change input to the char array:

getline(file, chararrayvar, ','); //avoids useless copying of the data.

these ideas give you

getline(file, person.name, ',');

or

strcpy(person.name, input.c_str());
Last edited on
Hey jonnin,

I ended up trying to do
1
2
3
getline(file,input,',');
char myChar[input.size() +1];
person.name = strcpy(myChar.c_str());


but it didn't work, i'm just not understanding at all how to do it, but thank you for helping.
Last edited on
heh, that is quite the mashup of what I said.

-- c++ does not allow variables as array sizes, they must be compile time constants.
strcpy function does return a value but its nothing you want right now. just treat it for now as if it were
void strcpy(char* destination, char* source);

or, as I said,
strcpy(person.name, input.c_str());

but again, you are better off all around just reading it directly.
getline(file, person.name, ',');
^^^
the above getline avoids using C string routines, which are frowned upon in c++
it avoids a useless copy, which consumes resources for no reason (tiny as it may be, try to be in the habit of not doing pointless data copies as those are one of the top 5 or so reasons for slow programs).

let me be very, very clear this time.

getline(file, person.name, ','); <--------------------- this is the line you want!
Last edited on
Topic archived. No new replies allowed.