Thread: Converting command line char *argv[] to int

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    2

    Converting command line char *argv[] to int

    Hey guys, First off I just want to say awesome site been very helpful.

    Anyways, I'm currently running into a problem while trying to convert a command line argument to an int.

    I'm running into a problem where I can't convert the data inside argv[1] to an int

    example argv[1] = 21231
    and it is grabbing the first data "2" representing it as an ascii code "50"

    This converts to ascii (If I am correct its because its assigning a char to an int and thus takes it as an ASCII code)
    Code:
    	
    int number = *(argv[1]);
    This creates a runtime error
    Code:
    int number = atoi(*argv[1]);
    TLDR: I'm trying to grab data from *argv[1] and convert it to an int


    FULL CODE
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv[]){
    	
    	//Grab data from Command line arguements
    	int length = strlen(argv[1]);	
    	int number = atoi(*argv[1]);
    	int startBase = atoi(*argv[2]);
    	int convertBase = atoi(*argv[3]);
    	
    	printf("Argument Amount: %d\n", argc-1);
    	printf("Number to be converted: %d\n", number);
    	printf("Base system %d\n", startBase);
    	printf("Converting to base %d\n", convertBase);
    	printf("Length %d\n", length);
    	return 0;	
    	
    }
    Thanks in advance

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    *argv[1] is a single character. atoi isn't a fan of single characters, and wants a string. So you should hand the string argv[1] to atoi, rather than a single character.

  3. #3
    Registered User
    Join Date
    Jan 2011
    Posts
    2
    Quote Originally Posted by tabstop View Post
    *argv[1] is a single character. atoi isn't a fan of single characters, and wants a string. So you should hand the string argv[1] to atoi, rather than a single character.
    Wow that simple... Thank you very much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 09:16 PM
  3. Replies: 4
    Last Post: 11-23-2003, 07:15 AM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM