
이번 글을 통해 배워갈 내용
- 스트링을 숫자로 변경해보겠습니다.
스트링을 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;
}
오늘도 즐거운 코딩하시길 바랍니다 ~ :)
참조 및 인용
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
'C++ > C++ 기타' 카테고리의 다른 글
| C++에서 new 없이 동적으로 2D 배열을 사용하는 방법에 대한 고찰 (0) | 2021.09.04 |
|---|---|
| C++ 타입캐스팅에 대한 생각과 팁 (0) | 2021.08.20 |
| C++에서 new로 동적 메모리 할당 후 null값 체크를 해야 할까요? (1) | 2021.07.20 |
| C++ 열거형의 간단한 정의와 예시 (1) | 2021.07.15 |
| C++ 배열없이 데이터 집약적으로 출석 저장해보기 (1) | 2021.07.12 |