DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Adding binary values from a file (http://www.daniweb.com/forums/thread65060.html)

DynamitMsk Dec 16th, 2006 10:34 am
Adding binary values from a file
 
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?

DynamitMsk Dec 16th, 2006 11:17 am
Re: Adding binary values from a file
 
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;
}

John A Dec 17th, 2006 12:57 am
Re: Adding binary values from a file
 
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


All times are GMT -4. The time now is 4:26 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC