C言語で、私が付けたargv[2]
数字int
とコード内の数字をどのように比較できるか疑問に思っています:
EX: prog.exe file.txt 74
========================
int n;
scanf ("%d", &n);
if (n > argv[2])
{
[...]
}
これらの異なる種類のデータを比較するにはどうすればよいですか?
コマンドラインのパラメータは文字列です。それらはそれぞれのタイプに変換する必要があります。個人的には、最初に整数変数とatoiを使用してargv[2]を解凍します。ユーザーが入力した値をに入力しn
、次のように比較します。
#include <stdio.h>
#include <string.h>
int n;
int argv_2;
int main(int argc, char *argv[])
{
int rc = 0;
/* Check for three arguments, program name and two passed. */
if(3 == argc)
{
argv_2 = strtol(argv[2], NULL, NULL, 10);
printf("Please enter a number for the vaue of the variable n\t: ");
scanf("%d", &n);
printf("\n\n");
if (n > argv_2)
{
printf("The value of n: %i is greater than argv[2]: %i\n",
n, argv_2);
}
else
{
printf("The value of n: %i is not greater than argv[2]: %i\n",
n, argv_2);
}
}
else
{
printf("Usage: ./test arg1 arg2 \n\n");
}
return rc;
}
argv[2]をwithinclude
foratoi()
に変換する場合は、単に関数を使用します。この関数は、文字列の非数値メンバーに遭遇するまで、文字列の最初の数字を単純に変換します。int
stdlib.h
atoi()