Hi folks.

I'm trying to do something I hope is very simple -- taking an argument placed after the program's name and storing it. So, if I type whatnumber 4 it will store the value 4, whatnumber 100 will store 100, etc. I've tried using int argc, char *argv[] instead of the usual void, but I don't understand exactly how this is passed -- for some reason this hasn't (yet) been covered in class and it's the first part of an assignment I'm trying to do.

Thanks guys.

much love,
sd

#include <stdio.h>


int main ( int argc, char *argv[] ) {
    int number = 4;
    printf("Number is %d", argv[1]);
    return 0;
}

Recommended Answers

All 2 Replies

>printf("Number is %d", argv[1]);
argv is a collection if strings. If the program is called whatnumber and you type whatnumber 4 to the command line, argv[1] will be the string "4". If you want to get an integer from that, you need to perform a conversion:

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

int main ( int argc, char *argv[] )
{
  if ( argc > 1 ) {
    int value = (int)strtol ( argv[1], NULL, 0 );

    printf ( "The string is \"%s\"\n", argv[1] );
    printf ( "The number is %d\n", value );
  }

  return 0;
}

Ah, of course. That makes perfect sense. Thanks for the assist, Narue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.