reading txt file into vector of struct

resolved
Last edited on
When you put "%s" in your formatted string, this means it has to format a "C-style string", not a C++ string class. Even so, the line of code here:
1
2
3
fscanf( fp, "%d %d %d %s %d %c %d\n", &xyz[i].hours,
 &xyz[i].minutes, &xyz[i].duration, &xyz[i].name, &xyz[i].number, 
&xyz[i].block, &xyz[i].room);

matches the %s to the address of the std::string member called name of the struct timeTableItem.

I am not gonna give you the direct answer/solution (that's for you to figure out), so here is a visual help. When you want to store a string using fscanf, you will normally do the following:
1
2
char cstr[64];
fscanf(fp, "%s", cstr); // make sure that whatever is scanned will fit cstr. 


Hint: It is possible to obtain the address of the first character of std::string class so it can be used with fscanf().
Thank you so much!!, i've been trying to get this for so long.

This is what i ended up trying and it worked. is this what you meant?
or is there a better way to code it.


1
2
3
4
5
6
7
8
9
10
11
for(int i=0; i<1; i++)
{
	
	xyz.push_back(timeTableItem());

	char cstr[5];

	fscanf( fp, "%d:%d %d %s %d %c %d \n", &xyz[i].hours, 
&xyz[i].minutes, &xyz[i].duration, cstr, &xyz[i].number, &xyz[i].block, &xyz[i].room);

	xyz[i].name = cstr;

Last edited on
"Better" is a subjective word. If we're doing it my way, I'd eliminate the temporary variable cstr. I said as a hint earlier:

Hint: It is possible to obtain the address of the first character of std::string class so it can be used with fscanf().


But for all intents and purposes, your solution is fine (it works and it does the job).
closed account (DSLq5Di1)
Have you not discovered <fstream>? it handles files in much the same way as using cout/cin.
vince1027 wrote:
Hint: It is possible to obtain the address of the first character of std::string class so it can be used with fscanf().

Don't do that. You should use the interface so the state remains consistent ( think string::size() )

@sloppy; also, stream redirection.
Last edited on
Topic archived. No new replies allowed.