954,184 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

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
Newbie Poster
14 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

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;
}
DynamitMsk
Newbie Poster
14 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

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

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You