C++/C++ 기타

C++에서 string을 int, uint혹은 long으로 변경하기

kimc 2021. 7. 21. 00:12


 

이번 글을 통해 배워갈 내용

  1.  스트링을 숫자로 변경해보겠습니다.

 

스트링을 int로 변경할때는

atoi 함수를 씁니다.

 

이때 주의 하실것은

 

1. 숫자의 자료형이 int인지 확인

2. 오버플로우 int의 경우 최대값 2147483647 을 초과하는지 확인

 

입니다. 

 

long이나 UINT의 경우 저는

 

atoi 대신에 stoul(string to unsigned long)을 많이 씁니다.

 

stoul 의 인자 값은 다음과 같습니다.
str - 변환할 문자열
pos - 처리된 문자 수를 저장할 정수 주소
base - 숫자 자릿수입니다.

 

추가 설명은 아래 링크를 참조하시면 됩니다(영문)

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

 

std::stoul, std::stoull - cppreference.com

Interprets an unsigned integer value in the string str. Discards any whitespace characters (as identified by calling isspace()) until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n (where n=bas

en.cppreference.com

 

아래는 위의 설명을 돕기 위한 예시입니다

 

한번 타이핑 해보시고

 

궁금한 사항이 있으시면 댓글 남겨주세요

 

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string myNumStr = "-2147483648";
    
    int myIntNo = atoi(myNumStr.c_str());
    cout<<myIntNo << endl;

    uint32_t myNo2 = stoul(myNumStr.c_str(), 0, 10);
    cout<< myNo2 << endl;
    
    long myNo3 = stoul(myNumStr.c_str(), 0, 10);
    cout<< myNo3 << endl;
    

    return 0;
}

 

 

 

오늘도 즐거운 코딩하시길 바랍니다 ~ :)

 

참조 및 인용

https://stackoverflow.com/questions/18037835/converting-string-to-unsigned-int-returns-the-wrong-result

 

Converting string to unsigned int returns the wrong result

I have the following string: sThis = "2154910440"; unsigned int iStart=atoi(sThis.c_str()); However the result is iStart = 2147483647 Does anybody see my mistake?

stackoverflow.com

 

https://en.cppreference.com/w/cpp/types/integer

 

Fixed width integer types (since C++11) - cppreference.com

int8_tint16_tint32_tint64_t(optional) signed integer type with width of exactly 8, 16, 32 and 64 bits respectivelywith no padding bits and using 2's complement for negative values(provided only if the implementation directly supports the type) (typedef) [e

en.cppreference.com

 

C++ Primer

 

 


https://codemasterkimc.tistory.com/35

 

C++ 이론을 배울수 있는 곳 정리

개요  C++을 배우는 책, 강의, 블로그, 링크 등을 공유합니다. (링크 및 간략한 설명을 하였으나 만약 원작자가 링크를 거는것을 원치 않을 경우 연락주시기 바랍니다.) 서적 https://www.amazon.com/Prime

codemasterkimc.tistory.com


 

728x90