letter
letter

Reputation: 91

How to change datatypes in c

I have a function, which adds the given arguments and prints the result.

With integer numbers, there were no problems at all. Used atoi to change string argument -> int.
e.g. : ./main 3 4 5 will print 12.

But if I have ./main 4.5 6 5.5 ?how do I do something like this in C? How can the function "see", that it has to change the argument types now to float?

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char* argv[] )
{
   int i , sum = 0;
   for(i=1; i < (argc); ++i)
     sum += atol(argv[i]);
   printf("%d\n", sum);

   return 0;

}

Upvotes: 2

Views: 286

Answers (4)

Mike -- No longer here
Mike -- No longer here

Reputation: 2092

Although I get an implicit declaration warning for strtod (because the linux manual doesn't tell me the correct includes to use), this code below does work:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
  int i;
  double sum=0;
  for(i=1; i < argc; ++i)
sum += strtod(argv[i],NULL);
  printf("%f\n", sum);

  return 0;

}

The manual also states the following as an issue with using atoi():

The atoi() function converts the initial portion of the string pointed to by  nptr  to  int.
The behavior is the same as

strtol(nptr, (char **) NULL, 10);

except that atoi() does not detect errors.

Upvotes: 0

gsamaras
gsamaras

Reputation: 73424

In , there is no function overloading as in , thus you should use atof, like this:

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char* argv[] )
{
   int i;
   double sum = 0;
   for(i = 1; i < (argc); ++i)
     sum += atof(argv[i]);
   printf("%f\n", sum);

   return 0;

}

to treat numbers as reals, not integers.

Output:

gsamaras@gsamaras-A15:~$ ./a.out 4.5 6 5.5
16.000000

since now 6 is treated like 6.0.


You might want to read this as well: How to convert string to float?

Upvotes: 3

abhiarora
abhiarora

Reputation: 10450

I have tested the code below. It will print the float number upto 2 decimal places.

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char* argv[] )
{
    int i;
    double sum = 0;
    for(i=1; i<argc; i++)
        sum += atof(argv[i]);
    printf("%.2f\n", sum);

    return 0;
}

Upvotes: 2

Roman
Roman

Reputation: 34

You should use double to store floating point numbers, atof to parse strings and the %f printf specifier.

Upvotes: 0

Related Questions