오리는 오늘도 꽥꽥

 

 

     

 

개요

[C언어] 문자열을 숫자로 바꾸기 - 1 (atoi, atof, atol)

문자열을 숫자로 바꿔주는 함수.

atoi, atol과 다른 점은 매개변수에 '기수'가 존재한다는 점이다.

즉, 16진수, 2진수 문자열을 굳이 10진수로 변환안해도 숫자 값으로 바꿀 수 있다.

strtod와 atof는 기능적으로 큰 차이가 없다.

 

strtol, strtoul

문자열을 정수형으로 반환해주는 함수

헤더파일 stdlib.h 에 포함되어있다.

strtol는 long, strtoul은 unsigned long값을 반환한다. (반환 값의 범위가 다르다.)

  • strtol 형식 : long int strtol (const char* str, char** endptr, int base);
  • strtoul 형식 : unsigned long int strtoul (const char* str, char** endptr, int base);

두번째 매개변수 endptr은 변환 중 멈춰진 위치를 저장하기 위한 포인터 변수이다. 이 값으로 숫자로 변환된 길이를 확인할 수 있다.

 

https://www.cplusplus.com/reference/cstdlib/strtol/?kw=strtol 

 

strtol - C++ Reference

function <cstdlib> strtol long int strtol (const char* str, char** endptr, int base); Convert string to long integer Parses the C-string str interpreting its content as an integral number of the specified base, which is returned as a long int value. If end

www.cplusplus.com

https://www.cplusplus.com/reference/cstdlib/strtoul/?kw=strtoul 

 

strtoul - C++ Reference

function <cstdlib> strtoul unsigned long int strtoul (const char* str, char** endptr, int base); Convert string to unsigned long integer Parses the C-string str, interpreting its content as an integral number of the specified base, which is returned as an

www.cplusplus.com

 

Example - strtol

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

int main(){

    char * string = "0xFF 0xAB 0xDD";
    char * stop;
    int radix;
    long length;
    long value;

    radix = 16;    
    value = strtol(string, &stop, radix);

    printf("%ld 개의 문자가 변환되었습니다.\n", stop - string);
    printf("변환된 16진수는 %ld입니다. \n", value);
    printf("변환되지 않은 문자열은 %s 입니다.\n", stop);

    return 0;
}

/*
4 개의 문자가 변환되었습니다.
변환된 16진수는 255입니다. 
변환되지 않은 문자열은  0xAB 0xDD 입니다.
*/

 

strtod

문자열을 실수형(double)로 반환해주는 함수.

헤더파일 stdlib.h 에 포함되어있다.

 

  • 형식 : double strtod (const char* str, char** endptr);

https://www.cplusplus.com/reference/cstdlib/strtod/?kw=strtod 

 

strtod - C++ Reference

A valid floating point number for strtod using the "C" locale is formed by an optional sign character (+ or -), followed by a sequence of digits, optionally containing a decimal-point character (.), optionally followed by an exponent part (an e or E charac

www.cplusplus.com

Example - strtod

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

int main(){

    char * string = "1.442E-10 5.442 2.31E5";
    char * stop;
    int radix;
    long length;
    double value;

    value = strtod(string, &stop);

    printf("%ld 개의 문자가 변환되었습니다.\n", stop - string);
    printf("변환된 문자열은 %E입니다. \n", value);
    printf("변환되지 않은 문자열은 %s 입니다.\n", stop);

    return 0;
}

/*
9개의 문자가 변환되었습니다.
변환된 문자열은 1.442000E-10입니다. 
변환되지 않은 문자열은  5.442 2.31E5 입니다.
*/

 

 

반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band