Orcka Orcka - 1 year ago 110
C Question

Command Line Input in C

I made a program that inputs thru the command line 2 variables.

If the input was 5 15 the output should be:

0.00 15.00 30.00 45.00 60.00

1.00 0.97 0.87 0.71 0.50

However in the command prompt whenever I type 5 15 I get:

0.00 0.00 0.00 0.00 0.00

0.00 0.00 0.00 0.00 0.00

Here is my code:

#include <stdio.h>
#include <math.h>

#define PI 3.14159265

char buff[256];
double length;
double stepSize;
double cosValue;
double val = PI / 180.0;
double i;

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

length = atof(argv[1]);
stepSize = atof(argv[2]);

for (i = 0; i < length; i++) {

double stepSizeEdit = stepSize * i;

printf("%.2lf ", stepSizeEdit);



for (i = 0; i < length; i++) {

double stepSizeEdit = stepSize * i;
cosValue = cos(stepSizeEdit * val);

printf("%.2lf ", cosValue);



The part that takes in the command line argument is this:

length = atof(argv[1]);
stepSize = atof(argv[2]);

Here I am converting the argv values from strings to doubles, is this incorrect?

Answer Source

When trying to compile your code, I get the following warning:

test.c:15:11: warning: implicit declaration of function 'atof' is invalid in C99
        length = atof(argv[1]);

This implicit declaration points you towards the problem. You did not include stdlib.h Include it and your program will work.

Without the include the function atof() is declared implicitly. When GCC doesn't find a declaration (which is the case if you don't include the header needed), it assumes this implicit declaration: int atof();, which means the function can receive whatever you give it, and returns an integer.

This is considered an error (implicit declarations) in newer C standards (C99, C11). However, gcc doesn't implement these standards by default, so you still get the warning with older standards (that you're using I suppose).

To better find these kind of errors I suggest your turn on and read the compiler warnings. You should also give this link a read to learn about them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download