Thread: help

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    3

    Angry help

    I am new to C and can't get my program to work. What is suposed to happen is at the command line I enter my program name and one argument. For example lets call my program myprog.

    myprog 3

    now after entering that it should spit out 4 (argv[1] + 1 = 4).

    so all to gether it should look like this

    myprog 3
    4

    But it dosent do that instead it does this.

    myprog 3
    -1073742996

    Now thats not right.

    When I compile there are no errors or warnings so
    I cant figure it out. here is the source. If somenone
    could correct it then repost it that would be great
    thanks!








    ------ CODE ---------

    Code:
    #include <stdio.h>
    
    int main(int argc, int argv[])
    {
    	int hex;	
    
    	if(argc == 2)
    	{
    		hex = dec2hex(argv[1]);
    		printf("%i\n", hex);
    	}
    	else if(argc == 1)
    	{
    		printf("Error: no arguments\n");
    	}
    	else
    	{
    		printf("Error: too many arguments\n");
    	}
    
    	return 1;
    }
    
    int dec2hex(int dec)
    {
    	return dec + 1;
    }
    Last edited by markavdh; 02-26-2003 at 05:03 PM.

  2. #2
    Registered User
    Join Date
    Feb 2003
    Posts
    76
    Should be:

    Code:
    #include <string.h>
    	if(argc == 2)
    	{
    		hex = atoi(argv[1]);
    		printf("%d\n", hex+1);
    	}

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    3
    I dont get what you mean by..

    You pass a char*
    It expects an int

  4. #4
    Registered User
    Join Date
    Feb 2003
    Posts
    76
    Originally posted by markavdh
    I dont get what you mean by..

    You pass a char*
    It expects an int
    You really are new to C. int is an integer, char* is a character string. These types cannot directly be converted. Use atoi to convert strings to integers.

  5. #5
    Registered User
    Join Date
    Feb 2003
    Posts
    3
    Ahh it works thank-you

  6. #6
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>char* is a character string
    No its not. Its a pointer to a char.

    For anyone thats interested, read about:
    Getting a number from the user
    Accessing command line args
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed