
이번 글을 통해 배워갈 내용
- C++에서 문자열을 숫자로 변하는 두 가지 방법
방법 1
std::stoi(), std::stof(), std::stod()를 활용해서
문자열을 정수, float 혹은 double로 변환
#include <iostream>
#include <string>
int main()
{
int i;
float f;
double d;
std::string str = "123";
try {
// string -> integer
int i = std::stoi(str);
std::cout << i << "\n";
// string -> float
float f = std::stof(str);
std::cout << f << "\n";
// string -> double
double d = std::stod(str);
std::cout << d << "\n";
}
catch (...) {
/* 예외처리 */
}
}
위와 같이 스택오버플로우에 나온 대로
stoi, stof, stod를 이용해서 숫자로 변환할 수 있습니다.
하지만 저는 이 방법 말고 방법 2를 더 애용합니다.
방법2
istringstream을 쓰는 방법
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
namespace learn::kimc::lib
{
int32_t ConvertStrToInt32(std::string str);
bool isInteger(const std::string& str);
int32_t ConvertStrToInt32(std::string str)
{
int32_t retVal = 0;
if (isInteger(str) == true)
{
std::istringstream(str) >> retVal;
}
else
{
/*예외처리*/
}
return retVal;
}
bool isInteger(const std::string& str)
{
return (str.find_first_not_of("0123456789") == std::string::npos);
}
// C++20
//bool isNumber(const string& str)
//{
// return std::ranges::all_of(str.begin(), str.end(),
// [](char c) { return isdigit(c) != 0; });
//}
}
int main()
{
const int32_t kTempNum = learn::kimc::lib::ConvertStrToInt32("1") ;
std::cout << kTempNum << "\n";
std::string tempStr = "abc";
std::cout << tempStr << " " << learn::kimc::lib::ConvertStrToInt32(tempStr) << "\n";
tempStr = "012345";
std::cout << tempStr << " " << learn::kimc::lib::ConvertStrToInt32(tempStr) << "\n";
tempStr = "444";
std::cout << tempStr << " " << learn::kimc::lib::ConvertStrToInt32(tempStr) << "\n";
}
위와 같이 istringstream을 사용해서 변환해주고
함수를 만들어서 예외처리를 해주면
웬만한 문자열 숫자 변환은 안정적으로 할 수 있습니다.
이상입니다.
오늘도 즐거운 코딩 하시길 바랍니다 ~ :)
참조 및 인용
https://stackoverflow.com/questions/7663709/how-can-i-convert-a-stdstring-to-int
How can I convert a std::string to int?
Just have a quick question. I've looked around the internet quite a bit and I've found a few solutions but none of them have worked yet. Looking at converting a string to an int and I don't mean A...
stackoverflow.com
C++ Primer
https://codemasterkimc.tistory.com/35
C++ 이론을 배울수 있는 곳 정리
개요 C++을 배우는 책, 강의, 블로그, 링크 등을 공유합니다. (링크 및 간략한 설명을 하였으나 만약 원작자가 링크를 거는것을 원치 않을 경우 연락주시기 바랍니다.) 서적 https://www.amazon.com/Prime
codemasterkimc.tistory.com
https://codemasterkimc.tistory.com/50
300년차 개발자의 좋은 코드 5계명 (Clean Code)
이번 글을 통해 배워갈 내용 좋은 코드(Clean Code)를 작성하기 위해 개발자로서 생각해볼 5가지 요소를 알아보겠습니다. 개요 좋은 코드란 무엇일까요? 저는 자원이 한정적인 컴퓨터 세상에서 좋
codemasterkimc.tistory.com
'C++ > C++ 기타' 카테고리의 다른 글
| visual studio 2019에서 줄맞춤 단축키, 줄정렬 단축키 (0) | 2021.10.16 |
|---|---|
| C++에서 Floating 값을 0과 비교하는 방법 (0) | 2021.10.07 |
| C++에서 new 없이 동적으로 2D 배열을 사용하는 방법에 대한 고찰 (0) | 2021.09.04 |
| C++ 타입캐스팅에 대한 생각과 팁 (0) | 2021.08.20 |
| C++에서 string을 int, uint혹은 long으로 변경하기 (1) | 2021.07.21 |