본문 바로가기
VisualStudio.C++.C#/코딩팁,함수활용,단편

std::string . 숫자 . stoi, stof, stol,stod, to_string

by i.got.it 2022. 2. 23.

 

 

std::string 을 숫자로 

stoi, stof, stol , stod : std::string 을 int, float, long, double 로 간단 변환. 

 

주의 : stoi 같은 경우 최대 10자리 정수까지만 변환된다.  

// C++11 부터. 

#include <string>



std::string my_str_i = "12345";

std::string my_str_i2 = "1234567890123456";


int i = std::stoi(my_str_i); // 정수로. base 지정하지 않으면 최대 10자리까지 정수변환. 

int64_t = std::stoi(my_str_i2); //주의 : 문자열 앞에서 부터 10개만 숫자로 변환됨.

 

 

 

숫자를 std::string 으로 to_string()

 


#include <string>


int my_i=123;

// to_string 인자는 모든 숫자타입가능.long,float,double,
std::string my_str = std::to_string(my_i);

 

to_string  주의사항 

float 이나 double 형을 입력시 소수점 이하 6자리까지만 표현됨.

 

 

소수점 이하 자리수 지정하여 문자열로 변환 하는 함수

- 인자 n  : 소수점 이하 자리 수 의미 하며 0이상 유효. 0이면 소수점없이 1의 자리까지만 표현, 

인자 n 을 음수로 입력하면 작용없이 소수점이하 6자리까지 문자열로 변환됨. 


#include <sstream>

template <typename T>
std::string to_string_with_precision(const T a_value, const int n = 6)
{
    std::ostringstream out;
    out.precision(n);
    out << std::fixed << a_value;
    return out.str();
}

 

 

상세

 

https://en.cppreference.com/w/cpp/string/basic_string/stol

 

std::stoi, std::stol, std::stoll - cppreference.com

(1) (since C++11) (2) (since C++11) (3) (since C++11) Interprets a signed integer value in the string str. Discards any whitespace characters (as identified by calling std::isspace) until the first non-whitespace character is found, then takes as many char

en.cppreference.com

 

 


첫 등록 : 2022.02.22

최종 수정 : 2022.03.12

단축 주소 : https://igotit.tistory.com/3511


 

댓글



 

비트코인




암호화폐       외환/나스닥/골드       암호화폐/외환/나스닥/골드 암호화폐/외환/나스닥/골드   암호화폐/외환/나스닥/골드
     
현물 |선물 인버스 |선물 USDT       전략매니저(카피트레이딩)     롤오버 이자 없는 스왑프리계좌
( 스왑프리 암호화폐도 거래 가능 )    
MT4, MT5 , cTrader 모두 지원     FTMO 계좌 매매운용. MT4,MT5