reading txt file into vector of struct
Oct 22, 2012 at 3:17am UTC
resolved
Last edited on Oct 22, 2012 at 4:28am UTC
Oct 22, 2012 at 3:59am UTC
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().
Oct 22, 2012 at 4:19am UTC
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 Oct 22, 2012 at 4:19am UTC
Oct 22, 2012 at 4:26am UTC
"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).
Oct 22, 2012 at 4:35am UTC
Have you not discovered <fstream>
? it handles files in much the same way as using cout/cin
.
Oct 22, 2012 at 5:38am UTC
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 Oct 22, 2012 at 5:38am UTC
Topic archived. No new replies allowed.