안녕하세요 char를 int로 변환하려고합니다. 나는 scanf
, "10101"을 통해 입력 된 문자 배열을 가지고 있으며 int 배열의 요소를 그 char 배열 요소와 같게 설정하려고합니다.atoi를 사용하여 int 배열에 char 배열 캐스팅
예를 입력 :
char aBuff[11] = {'\0'};
int aDork[5] = {0};
scanf("%s", aBuff); //aBuff is not equal to 10101, printing aBuff[0] = 1, aBuff[1] = 0 and so on
가 지금은10101
1
것
aBuff[0]
동일하게
aDork[0]
를 원한다.
다음은 내가 지금까지 가지고있는 것입니다.
//seems to not be working here
//I want aDork[0] to = aBuff[0] which would be 1
//But aDork[0] is = 10101 which is the entire string of aBuff
//aBuff is a char array that equals 10101
//aDork is an int array set with all elements set to 0
int aDork[5] = {0}
printf("aBuff[0] = %c\n", aBuff[0]); //value is 1
aDork[0] = atoi(&aBuff[0]); //why doesnt this print 1? Currently prints 10101
printf("aDork[0] = %d\n", aDork[0]); //this prints 1
printf("aBuff[1] = %c\n", aBuff[1]); //this prints 0
printf("aBuff[2] = %c\n", aBuff[2]); //this prints 1
주조는 (강제) 유형 변환입니다. 'atoi '와 같이 구문 분석하지 않습니다. – Deduplicator
그래서 문자 배열의 각 요소를 리터럴 int 1 또는 int 0이되도록하려면 어떻게해야합니까? – Yawn
char 값과 int 값 (한자리 숫자)의 차이는 0x30 ('0')입니다. aDork [0] = aBuff [0] - '0'; aDork [1] = aBuff [1] - '0'; etc. – user3629249