Re: how to pass vector<char> as parameter?
Jack wrote:
I am working on a file parser.
void process_file(std::string filename)
{
//FILE *afile;
char c;
ifstream infile(filename.c_str ());
//if ((afile = fopen (filename, "rt")) == NULL)
//{
// exit(0);
//}
if(!infile)
{
cerr<<"Can't open file " << filename << endl;
exit(-1);
}
//fileData = (char *) malloc (50000);
// memset (fileData, 0, sizeof(fileData));
// fread (fileData, sizeof(char), sizeof(fileData), afile);
while (infile >> c)
{
fileData.push_back(c);
}
printf ("Parsing %s\n", filename.c_str());
parse (fileData, fileData.size());
}
void parse (vector<char> buf, long count)
{
int i,j;
char *tokens[256];
long cnt = 0; // count for number of tokens
char c;
bool ignore = false;
int k = 0;
char buff[256];
PCSTR buf2 = &buf[0];
// char p;
std::string buf3;
// static long token_count = 0;
for (;;) {
memset (buff, 0, 256);
trim (buf2);
is_comment(buf2[0], buf2[1]);
if (one_line_comment)
{
while (*buf2 != '\n') <<<<<<<<<<<< when I took a view at buf2, all \n
disappeared
buf2++;
buf2++; // Skip tail \n
Jack:
1. This is happening because you use >> operator. It does not have to do
with std::vector. Use std::istream::get() like this:
while (infile.get(c))
{
//
}
2. How does this code compile?
PCSTR buf2 = &buf[0];
trim (buf2);
Isn't the trim function modifying buf2 here? Don't you need non-constant
buffer:
char* buf2 = &buf[0];
3. You don't need to pass the size of the vector, because std::vector
knows its own size.
4. You code will not work because you are passing fileData by value. You
must pass it by reference;
void parse (vector<char>& buf, long count)
{
}
5. It is almost always best to pass standard library objects by
reference even when it is not necessary. If the object is not modified
then pass by const reference:
void process_file(const std::string& filename)
{
}
6. What is "one_line_comment? It would seem to be a global variable. It
is almost always wrong to use global variables in C++. Why not just
if(is_comment(buf2)
{
}
7. I would recommend you read a good introductory book on modern C++,
one that emphasizes (correct) usage of the standard library. You have a
lot of bad programming habits.
--
David Wilkinson
Visual C++ MVP