Hello, I'm working o a function that takes a file with binary numbers and returns the sum of those numbers. Here's where I'm now

int Sum (char *fileName)
{
char * numEnd;
long temp(0);
int result(0);
string line;
 ifstream file (fileName);
  if (file.is_open())
  {
    while (! file.eof() )
    {
      getline (file,line);
//Convert line to an long and sum up with the rest 
      temp = strtol(line, &numEnd, 2);
      result = result + temp;    
//Done
    }
// close the stream
    file.close();
  }
return result;
}

and here's an error I'm getting when building it:
error C2664: 'strtol' : cannot convert parameter 1 from 'std::string' to 'const char *'

I thought strtol needed a pointer to the string, but changing line to pointer to line didn't help. Anyone can point me in a right direction?

OK, I got it. Any comments on code quality or improvements are still welcome!

int Sum (char *fileName)
{
char * numEnd;
long temp(0);
int result(0);
string line;
 ifstream file (fileName);
  if (file.is_open())
  {
    while (! file.eof() )
    {
      getline (file,line);
//Convert line to an int and sum up with the rest 
      char *linePt = &line[0];
      temp = strtol(linePt, &numEnd, 2);
      result = result + temp;    
//Done
    }
// close the stream
    file.close();
  }
return result;
}

It's because strtol was an old C function written far before C++ strings were invented. Although C++ strings have overloaded functions to make transitions from the older-style char strings to C++ strings and vice-versa, this problem can't be as transparently solved when passing a C++ string to a function that is expecting a char string. To remedy this, C++ strings include a nifty member function called c_str() that can quickly return the char string equivalent. Thus, you could code it like this:

temp = strtol(line.c_str(), &numEnd, 2);

Better yet, use the C++ streams, the modern equivalent of a lot of the old C string functions, rather than mixing C and C++.

Hope this helps

commented: Yes, it does helps ~~ SunnyPalSingh +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.