By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,493 Members | 1,296 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,493 IT Pros & Developers. It's quick & easy.

read data from file into structure in C++ ?

P: n/a
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

Nov 11 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Ian
tv****@hotmail.com wrote:
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
Nov 11 '05 #2

P: n/a
tv****@hotmail.com wrote:
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
Nov 11 '05 #3

P: n/a

You can try using class and vector

Nov 11 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.