Atof not working?

Dee picture Dee · Oct 10, 2011 · Viewed 9.7k times · Source

So I'm writing a program for a school project, and part of it requires having a user put in a random number at the command line. The program then uses atof to convert the number to a float so I can do some math with it. That part of the program looks like:

#include <iostream>
#include <cstdlib>
#include "bmplib.h" //this is just something the prof. gave us to help read the image
#include <cmath> //i might use this later in the program

#define nummethods 2
using namespace std;

unsigned char input[256][256][3];
unsigned char bg [256][256][3];
unsigned char output[256][256][3];
unsigned char m[2][256][256];

int main(int argc, char *argv[])
{

  int h,i,j,k;
  double x,y,z;

  //code to read img here and make sure user puts correct number of arguments in 
 //command line

  for (i=0;i<256;i++){
    for(k=0;k<3;k++){
      y = y + input[i][0][k];
    }
  }

 cout >> y >> endl; //this is giving me 36,164,75 which in RGB is green       

 x = atof(argv[3]); //the number was the 3rd thing typed in at the command line
 cout << x << endl;

 z = x + y; //this isn't the exact program, but you get the idea
 cout << z << endl;

//there's some more code after this written by the prof. that manipulates the image,
//but i don't think its relevant since it does not use the argv[3] value
}

The program compiled but it didn't work right. I tested it by adding a cout << x; and it showed that atof was giving me the wrong number. For example, when put 5.0 as my number into the command line, it showed that my x was 379.7465. Any idea what's wrong?

Answer

Stephen picture Stephen · Oct 10, 2011

Are you including stdlib.h ??

I find if i dont explicitly import stdlib.h the code complies and runs, but atof returns 0, when i include stdlib.h it returns the value as expected.

Im using the gcc for c code. I assume its the same for c++.