17

ユーザーに2つのパラメーターを渡すか、空白のままにしてほしい。例えば:

./program 50 50

また

./program

使ってみたところint main(int argc, char *argv[])、最初に変更char *argv[]するint *argv[]ことでしたが、うまくいきませんでした。私が欲しいのは、ユーザーに0から100までの2つの整数を入力することです。したがって、2つの整数でない場合は、エラーが発生するはずです。

私は(C#でプログラミングしていたように)型でエラーを出すことを考えていましたが、入力するものが何であれ、argv[1]は常に「char」型になります。

だから私がしたことは

for (int i = 0; i <= 100; i++) {
    //printf("%d", i);
    if (argv[1] == i) {
        argcheck++;
        printf("1st one %d\n", i);
    }
    else if (argv[2] == i) {
        argcheck++;
        printf("2nd one %d\n", i);
    }

これも機能しません。また、コンパイル時に警告が表示されますが、たとえばで変更argvすると、セグメンテーション違反(コアダンプ)エラーが発生します。atoi(argv[1])

この問題を解決する簡単な方法が必要です。

編集:

だから私はで修正しましatoi()た、それがセグメンテーション違反を与えていた理由は私がパラメータを持っていないときにnull値でそれを試していたからです。そこで、条件を追加して修正しました。しかし今問題は、値が

./program asd asd

その場合、の出力はatoi(argv[1])0になります。この値を変更する方法はありますか?

4

8 に答える 8

30

Don't use atoi() and don't use strtol(). atoi() has no error checking (as you found out!) and strtol() has to be error-checked using the global errno variable, which means you have to set errno to 0, then call strtol(), then check errno again for errors. A better way is to use sscanf(), which also lets you parse any primitive type from a string, not just an integer, and it lets you read fancy formats (like hex).

For example, to parse integer "1435" from a string:

if (sscanf (argv[1], "%i", &intvar) != 1) {
    fprintf(stderr, "error - not an integer");
}

To parse a single character 'Z' from a string

if (sscanf (argv[1], "%c", &charvar)!=1) {
    fprintf(stderr, "error - not a char");
}

To parse a float "3.1459" from a string

if (sscanf (argv[1], "%f", &floatvar)!=1) {
    fprintf(stderr, "error - not a float");
}

To parse a large unsigned hexadecimal integer "0x332561" from a string

if (sscanf (argv[1], "%xu", &uintvar)!=1) {
    fprintf(stderr, "error - not a hex integer");
}

If you need more error-handling than that, use a regex library.

于 2012-08-23T13:21:06.483 に答える
14

This will do:

int main(int argc, char*argv[])
{
   long a,b;
   if (argc > 2) 
   {
      a = strtol(argv[1], NULL, 0);
      b = strtol(argv[2], NULL, 0);
      printf("%ld %ld", a,b);
   }
   return 0;
}
于 2012-08-23T12:11:49.677 に答える
5

The arguments are always passed as strings, you can't change the prototype of main(). The operating system and surrounding machinery always pass strings, and are not able to figure out that you've changed it.

You need to use e.g. strtol() to convert the strings to integers.

于 2012-08-23T12:02:24.190 に答える
2

You want to check whether

  1. 0 or 2 argument is received
  2. two values received are between 0 and 100
  3. received argument is not a string. If string comes sscanf will return 0.

Below logic will helps you

int main(int argc, char *argv[])
{
    int no1 = 0, no2 = 0, ret = 0;

    if ((argc != 0) && (argc != 2)) 
    {
        return 0;
    }

    if (2 == argc)
    {
        ret = sscanf(argv[1], "%d", &no1);
        if (ret != 1)return 0;
        ret = sscanf(argv[2], "%d", &no2);
        if (ret != 1)return 0;          

        if ((no1 < 0) || (no1 >100)) return 0;
        if ((no2 < 0) || (no2 >100)) return 0;          
    }

    //now do your stuff
}
于 2012-08-23T14:12:18.863 に答える
0

The things you have done so innocently are blunder in C. No matter what, you have to take strings or chars as your arguments and then later you can do whatever you like with them. Either change them to integer using strtol or let them be the strings and check each char of the string in the range of 48 to 57 as these are the decimal values of char 0 to 9. Personally, this is not a good idea and not so good coding practice. Better convert them and check for the integer range you want.

于 2012-08-23T12:09:20.750 に答える
0

You can still use atoi, just check whether the argument is a number first ;)
btw ppl will tell you goto is evil, but they're usually brainwashed by non-sensible "goto is bad", "goto is evil", "goto is the devil" statements that were just tossed out without elaboration on the internet.
Yes, spaggethi code is less managable. And goto in that context is from an age where it replaced functions...

    int r, n, I;
    for (I = 0; I < argc; ++I)
    {
      n = 0;
      do
        if ( !((argv + I) [n] >= '0' && (argv + I) [n] <= '9') )
        {
          err:
            fprintf(stderr,"ONLY INTEGERS 0-100 ALLOWED AS ARGUMENTS!\n");
            return 1;
        }
      while ((argv + I) [++n] != '\0')
      r = atoi(argv[I]);
      if (r > 100)
        goto err;
    }
于 2015-04-29T22:29:06.127 に答える
-1

You can not change the arguments of main() function. So you should just use atoi() function to convert arguments from string to integer.

atoi() has its drawbacks. Same is true for strtol() or strtoul() functions. These functions will return a 0 value if the input to the function is non-numeric i.e user enters asdf or anything other than a valid number. To overcome this you will need to parse the string before passing it to atoi() and call isdigit() on each character to make sure that the user has input a valid number. After that you can use atoi() to convert to integer.

于 2012-08-23T12:04:47.770 に答える
-1
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main(int argc,char *args[])
{
    int i,sum=0;
    for(i=0;i<=argc;i++)
    {
        printf("\n The %d argument is: %s",i,args[i]);
    }
    printf("\nTHe sum of given argumnets are:");
    for(i=1;i<argc;i++)
    {
       int n;
       n=atoi(args[i]);
       printf("\nN=%d",n);
       sum += n;
    }
    printf("\nThe sum of given numbers are %d",sum);
    return(0);

  }

check this program i added another library stdlib.h and so i can convert the character array to string using function atoi.

于 2015-11-21T12:53:00.467 に答える