read data from file into structure in C++ ?

T

tvn007

I wrote the code below to read data from file into structure using C.
However, I would like to convert it to C++.
Could someone please give me some hints. I am not that famaliar with
C++

Thanks in advance
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct test {

char enabled,
put[20];
int type;
char desc[20];
} *results_ptr, Result[50];

/////////////////////////////////////////////////////////
void input (string& inputfile){
const int size = 2048;
char *ptr, buffer[size];
ifstream in(inputfile.c_str());
if (!in.is_open()) {
cerr <<"Cannot open file" "" <<inputfile<<endl;
exit (EXIT_FAILURE);
}
results_ptr = Result;
while (in.getline (buffer, size)){
ptr = strtok(buffer,"-,\t\n");
if (*ptr == '#')
continue;

results_ptr->enabled = *ptr;
ptr = strtok(NULL,"-,\t\n");

while (*ptr == ' ') ptr++;
(void)strcpy(results_ptr->put,ptr);
ptr = strtok(NULL,"-,\t\n");

while (*ptr == ' ') ptr++;
results_ptr->type = atoi(ptr);
ptr = strtok(NULL,",\t\n");

while (*ptr == ' ') ptr++;
(void)strcpy(results_ptr->desc,ptr);
results_ptr++;
}

in.close();
return ;
}
///////////////////////// INPUT //////////////////////////////////////
##############################################
N, banana, 1, yellow
Y, grass, 2, green
 
I

Ian

I wrote the code below to read data from file into structure using C.
However, I would like to convert it to C++.
Could someone please give me some hints. I am not that famaliar with
C++
Converting from C code isn't a good idea, you will perpetuate the C
idioms into you new version.

Start form scratch, thinking C++ objects - streams and strings.

Ian
 
J

John Harrison

I wrote the code below to read data from file into structure using C.
However, I would like to convert it to C++.
Could someone please give me some hints. I am not that famaliar with
C++

First thing you need is a string tokenizer that works on C++ strings (to
replace strtok). You could write your own but that's a project in
itself, so I'd recommend the one from boost

http://www.boost.org/libs/tokenizer/index.html

Completely free.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top