argv[]를 int로 받으려면 어떻게 해야 합니까?
나는 다음과 같은 코드가 있습니다.
int main (int argc, char *argv[])
{
printf("%d\t",(int)argv[1]);
printf("%s\t",(int)argv[1]);
}
그리고 쉘에서 나는 이것을 합니다.
./test 7
하지만 첫 번째 printf 결과는 7이 아닙니다. 어떻게 하면 argv[]를 int로 얻을 수 있습니까? 감사합니다.
argv[1]
문자열에 대한 포인터입니다.
다음을 사용하여 가리키는 문자열을 인쇄할 수 있습니다.printf("%s\n", argv[1]);
문자열에서 정수를 가져오려면 먼저 변환해야 합니다.사용하다strtol
문자열을 로 변환하다int
.
#include <stdio.h>
#include <errno.h> // for errno
#include <limits.h> // for INT_MAX, INT_MIN
#include <stdlib.h> // for strtol
int main(int argc, char *argv[])
{
char *p;
int num;
errno = 0;
long conv = strtol(argv[1], &p, 10);
// Check for errors: e.g., the string does not represent an integer
// or the integer is larger than int
if (errno != 0 || *p != '\0' || conv > INT_MAX || conv < INT_MIN) {
// Put here the handling of the error, like exiting the program with
// an error message
} else {
// No error
num = conv;
printf("%d\n", num);
}
}
이 Q&A는 C++가 아닌 플레인 C에 관한 것입니다. (C++에 대한 답이 다른지는 모르겠지만, 당신이 포함해야 할 수도 있습니다.cstring
대략.)
기본 용법
"긴 문자열"(strtol
) 함수는 이에 대한 표준("긴"은 "int"보다 훨씬 큰 숫자를 포함할 수 있습니다.사용 방법은 다음과 같습니다.
#include <stdlib.h>
long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)
우리는 십진법을 사용하기 때문에, 기본은 10입니다.그endpointer
인수는 "첫 번째 잘못된 문자", 즉 첫 번째 숫자가 아닌 문자로 설정됩니다.상관없으면 인수를 다음으로 설정합니다.NULL
표시된 대로 포인터를 전달하는 대신
오류 확인(1)
non-digits가 발생하지 않도록 하려면 "null terminator"로 설정해야 합니다.\0
는 항상 C:에서 문자열의 마지막 문자입니다.
#include <stdlib.h>
char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string
오류 확인(2)
man 페이지에서 언급했듯이, 당신은errno
오류가 발생하지 않았는지 확인합니다(이 경우 오버플로 또는 언더플로).
#include <stdlib.h>
#include <errno.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
// Everything went well, print it as 'long decimal'
printf("%ld", arg);
오류 확인(3)
sigjuice가 지적했듯이, 함수는 빈 문자열을 기꺼이 무시하고 설정되지 않습니다.errno
길이가 0인 문자열에 다음이 포함되어 있기 때문에 null 바이트 검사도 트리거되지 않습니다.\0
처음부터그래서 우리는 또 다른 수입과 또 다른 확인이 필요합니다.
#include <string.h>
if (strlen(argv[1]) == 0) {
return 1; // empty string
}
정수로 변환
그래서 지금 우리는 이것에 갇혀 있습니다.long
하지만 우리는 종종 정수로 작업하기를 원합니다.변환하는 방법long
의 상태로.int
우리는 먼저 그 숫자가 제한된 용량 내에 있는지 확인해야 합니다.int
이를 위해 두 번째 if-statement를 추가하고, 일치하면 그냥 캐스팅할 수 있습니다.
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
if (strlen(argv[1]) == 0) {
return 1; // empty string
}
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number
printf("%d", arg_int);
이 검사를 수행하지 않을 경우 발생하는 결과를 보려면 코드를 테스트하십시오.INT_MIN
/MAX
만일의 경우의2147483647(231)보다 큰 숫자를 전달하면 넘치고 음수가 되는 것을 알 수 있습니다.또는 -2147483648(-2-131)보다 작은 숫자를 전달하면 언더플로가 발생하여 양수가 됩니다.이 한계를 초과하는 값이 너무 커서 정수에 적합하지 않습니다.
전체 예
#include <stdio.h> // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h> // for errno
#include <limits.h> // for INT_MIN and INT_MAX
#include <string.h> // for strlen
int main(int argc, char** argv) {
if (strlen(argv[1]) == 0) {
return 1; // empty string
}
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number plus a newline
printf("Your value was: %d\n", arg_int);
return 0;
}
Bash에서는 다음을 사용하여 테스트할 수 있습니다.
cc code.c -o example # Compile, output to 'example'
./example $((2**31-1)) # Run it
echo "exit status: $?" # Show the return value, also called 'exit status'
용사를 합니다.2**31-1
와 그은번를인야하고해쇄호것▁the,하▁print▁and,0
2-1이31 범위 내에 있기 때문입니다.합격하면2**31
대에없신(이없)))-1
는 ), 종료됩니다.1
.
에도 사용자 검사를 할 수 . 이외에도사구수있현다습니할를사검지정용자▁beyondcheck다있니습수▁at이▁whether▁you:▁checks▁test▁an▁the구현할▁custom▁argument외▁implement,▁passed▁this▁can에▁user▁( 사용자가 인수를 전달했는지 테스트합니다(체크).argc
을 테스트합니다.
사용할 수 있습니다.strtol
이를 위해:
long x;
if (argc < 2)
/* handle error */
x = strtol(argv[1], NULL, 10);
그하는 경우에는 또C99 이는strtoimax
.
은 기능을 할 수 .int atoi (const char * str);
.
을 포함해야 .#include <stdlib.h>
다음과 같은 방식으로 기능을 사용합니다.int x = atoi(argv[1]);
필요한 경우 여기에 추가 정보: atoi - C++ 참조
/*
Input from command line using atoi, and strtol
*/
#include <stdio.h>//printf, scanf
#include <stdlib.h>//atoi, strtol
//strtol - converts a string to a long int
//atoi - converts string to an int
int main(int argc, char *argv[]){
char *p;//used in strtol
int i;//used in for loop
long int longN = strtol( argv[1],&p, 10);
printf("longN = %ld\n",longN);
//cast (int) to strtol
int N = (int) strtol( argv[1],&p, 10);
printf("N = %d\n",N);
int atoiN;
for(i = 0; i < argc; i++)
{
//set atoiN equal to the users number in the command line
//The C library function int atoi(const char *str) converts the string argument str to an integer (type int).
atoiN = atoi(argv[i]);
}
printf("atoiN = %d\n",atoiN);
//-----------------------------------------------------//
//Get string input from command line
char * charN;
for(i = 0; i < argc; i++)
{
charN = argv[i];
}
printf("charN = %s\n", charN);
}
이게 도움이 되길 바랍니다.행운을 빕니다.
언급URL : https://stackoverflow.com/questions/9748393/how-can-i-get-argv-as-int
'programing' 카테고리의 다른 글
다중 처리 - 파이프 대 대기열 (0) | 2023.06.18 |
---|---|
Firebase - 암호 재설정 랜딩 페이지 사용자 정의 (0) | 2023.06.18 |
스케줄링된 작업 만들기 (0) | 2023.06.18 |
새 줄 서식을 Mac에서 Windows로 변환 (0) | 2023.06.18 |
Float에서 최신 버전으로 Firebase Messaging을 구성하는 방법은 무엇입니까? (0) | 2023.06.18 |