?
Solved

simple command line input program questions

Posted on 2003-03-15
14
Medium Priority
?
198 Views
Last Modified: 2010-04-15
#include<stdio.h>
#include<ctype.h>
 
int main (int argc, char *argv[]){

int x, y;

// Error if only 1 input
if (argc != 3){

printf("Must have two arguments.\n");
return -1;
}

// Error if input not numbers
if ( (isdigit ( argv[2] ) && isdigit ( argv[3] ) )==0 ){

printf("Arguments must be a number.\n");
return 0;
}

x = argv[2];
y = argv[3];


printf("%d\n",x*y);


}

I'm just starting C, and I think I declared x and y wrong...kinda confused with pointers...can anyone tell me what's wrong? This program just multiplys two command line inputs...also...if the user inputs program 45 45h...will my error handling method work for non numbers?
0
Comment
Question by:AZN_Wang
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 2
  • +1
14 Comments
 
LVL 2

Expert Comment

by:ewest
ID: 8144956
Arrays in C are zero indexed. In other words the first index of an array is 0. The maximum index of an array is one less than the size of the array.

When reading the command line via argv, the argv[0] is the command name, argv[1+i] are subsequent command line arguments.

In your code, you are expecting two command line arguments, x and y. These should be at argv[1] and argv[2].

A simple program to demonstrate this:

#include <stdio.h>

int
main(int argc, char **argv)
{
   int i;

   printf("argc = %d\n", argc);
   for (i = 0; i < argc; i++) {
       printf("argv[%d] = %s\n", i, argv[i]);
   }
   return 0;
}

I recommend that as you are learning programming to attempt  short programs of this type to gain a better understanding of programming constructs and language features.

One other point: x and y are input as strings, before you can add these, you will want to convert from the string representation of the numbers to their binary equivalents. Refer to your fave C language text for atoi or better yet, strtol.

0
 
LVL 5

Expert Comment

by:ecw
ID: 8144965
You're confusing pointers with values pointed to,

  if ((isdigit(*argv[2]) && isdigit(*argv[3])) == 0){
/* ie. are the first chars of argv[2] and argv[3] digits */
    printf("Arguments must be a number.\n");
    return 1;
  }
/* now convert the char text of args 2 and 3 to ints */
  x = atoi(argv[2]);
  y = atoi(argv[3]);


0
 

Author Comment

by:AZN_Wang
ID: 8145015
it says implicit declaration of 'atoi' line 21
x = atoi(argv[1]);

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:AZN_Wang
ID: 8145030
also...
when i test the program with
program 3d 3d it still returns 9
its suppose to return the error message
right now...program d d will return the error message
0
 
LVL 5

Expert Comment

by:Kocil
ID: 8145390
isdigit() work on single characters. If your prorgam is called with multicharacters number like this

multiply 123 456

Then you can only check the input with atoi.
atoi reference:
===================
int  atoi ( const char * string );
Convert string to integer.
  Parses string interpreting its content as a number and Return Value.
  The converted integer value of the input string.
  On overflow the result is undefined.
  If an error occurs 0 is returned.
===================

So you may use

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

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

int x, y;

// Error if only 1 input
if (argc != 3){
  printf("Must have two arguments.\n");
  return -1;
}

x = atoi(argv[1]);
y = atoi(argv[2]);

// Error if input not numbers
if ( (argv[1][0]!='0' && (x == 0)) || ((argv[2][0]!='0') && (y==0)) ) {
  printf("Arguments must be a number.\n");
  return 0;
}

printf("%d\n",x*y);

}

Unfortunatelly, this program won't work if you pass the multi ZERO like this
multiply 123 000
multiply 00 456

PS:
0
 

Author Comment

by:AZN_Wang
ID: 8145718
// Error if input not numbers
if ( (argv[1][0]!='0' && (x == 0)) || ((argv[2][0]!='0') && (y==0)) ) {
 printf("Arguments must be a number.\n");
 return 0;
}

The above doesn't work at all...=/
i tried
program 4d 3d
program d3 d3
program 3d 3

all of them doens't return the error message
0
 
LVL 2

Expert Comment

by:ewest
ID: 8145756
There was a reason I suggested strtol as a better function than atoi. strtol and strtoul will detect errors. atoi on the other hand will not detect errors in a robust manner.

    char *ptr;
    long val;

    val = strtol(input_string, &ptr, 10);
    if (ptr == input_string) {
         /* error, no conversion */
    }
    if (ptr != '\0') {
         /* extra non-numeric chars detected */
    }

Refer to the strtol man pages for all the fine details.

Note to kocil:
>>> Then you can only check the input with atoi.
Wrong. strtol, strtoul, strtod, ... And then there is the ever popular "code the conversion yourself" approach.
0
 
LVL 5

Expert Comment

by:Kocil
ID: 8146128
>>> Then you can only check the input with atoi.

Yah. Big mistake. I should said :

Then you can't chek it with isdigit(*argv[0])


0
 

Author Comment

by:AZN_Wang
ID: 8146586
x = strtol(argv[1], &ptr1, 10);
y = strtol(argv[2], &ptr2, 10);

if (ptr1 == argv[1] || ptr2 == argv[2]) {
        /* error, no conversion */
   }
   if (ptr1 != '\0' || ptr2 != '\0') {
       printf("Arguments must be a number.\n");
   }

So would something like that work?
sorry ... really stuipd at C
0
 
LVL 2

Expert Comment

by:ewest
ID: 8146823
Did you try it? :-)

<rant>
I'm constantly amazed at the reluctance of new coders to just try to compile and run... Quick and dirty toss-away programs *are* your friends! Use them to test your implementations; use them to confirm correctness of code. There is a lot to be said for "field experience".
</rant>

...and yes, that is a way to code the conversion.

(AZN Wang: Please, don't be intimidated by my rant... Did you refer to the man pages for the strtol and strtoul functions? Do you understand why these routines are prefered to atoi?)

0
 

Author Comment

by:AZN_Wang
ID: 8147539
I did try it to no avail...
0
 

Author Comment

by:AZN_Wang
ID: 8147563
I tried doing this:
for(i=0; argv[1][i] !='\0';i++){
if (isdigit[argv[1][i] = 0)
 printf("Arguments must be a number.\n");

}

but doens't work =/
0
 

Author Comment

by:AZN_Wang
ID: 8147607
Ok, i did this and it works:
for(z=1; argc-1;z++){
for(i=0; argv[z][i] !='\0';i++){

     if (isdigit(argv[z][i]) == 0){
 printf("Arguments must be a number.\n");
 return 0;
     }
}
}

but can someone explain to me how atoi and strtol works? and what it does? thx!
0
 
LVL 2

Accepted Solution

by:
ewest earned 225 total points
ID: 8147943
strtol attempts to convert a string representation of a number into a binary value. It understands base conversions. For example "0x1234" is understood to be a hex value. Similarly, "01234" is treated as an octal value.

Processing of a string stops at the first non-numeric character. Leading whitespace chars are skipped over. The 2nd argument is a pointer to the address where the processing ended. If the pointer is to the beginning of the string, no conversion was possible. If the pointer is not to the address at the end of the string, additional non-numeric characters were detected. This argument may be passed as NULL, if desired.

The last argument to strtol is the base to be used by the conversion. If it is 10, the input string is expected to contain characters representing decimal values. Similarly, if the value is 2, binary conversion is attempted. If the value is 0, the input string may contain any valid hex, octal, or decimal numeric representation: "0x1234", "01234", "1234".

atoi is effectively

    strtol(input_string, (char **)NULL, 10)

This form of strtol masks errors. Does a return of 0, mean an error occured or the string really was "0".

Refer to the man pages, or your fave C text for the fine details.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question