Programing

C ++에서 숫자를 문자열로 변환하거나 그 반대로 변환하는 방법

lottogame 2020. 7. 14. 08:19
반응형

C ++에서 숫자를 문자열로 변환하거나 그 반대로 변환하는 방법


이 질문은 매주 질문되므로이 FAQ 는 많은 사용자에게 도움 될 수 있습니다.

  • C ++에서 정수를 문자열로 변환하는 방법

  • C ++에서 문자열을 정수로 변환하는 방법

  • C ++에서 부동 소수점 숫자를 문자열로 변환하는 방법

  • C ++에서 문자열을 부동 소수점 숫자로 변환하는 방법


C ++ 11 업데이트

의로서 C++11표준 문자열 - 투 - 수 전환 및 그 반대의 표준 라이브러리에 내장되어 있습니다. <string>문단 21.5 에 따라 다음의 모든 기능이 제공됩니다 .

문자열을 숫자로

float              stof(const string& str, size_t *idx = 0);
double             stod(const string& str, size_t *idx = 0);
long double        stold(const string& str, size_t *idx = 0);
int                stoi(const string& str, size_t *idx = 0, int base = 10);
long               stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long      stoul(const string& str, size_t *idx = 0, int base = 10);
long long          stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);

이들 각각은 문자열을 입력으로 사용하여 숫자로 변환하려고 시도합니다. 유효한 숫자를 구성 할 수없는 경우 (예 : 숫자 데이터가 없거나 숫자가 범위를 벗어난 경우) 예외가 발생합니다 ( std::invalid_argument또는 std::out_of_range).

변환이 성공하고하면 idx되지 0, idx디코딩에 사용되지 않은 첫 번째 문자의 인덱스를 포함합니다. 마지막 문자 뒤에 인덱스가 될 수 있습니다.

마지막으로, 적분 유형은 9보다 큰 자릿수에 대해 밑을 지정할 수 있으며 알파벳은 ( a=10까지 z=35) 로 가정 됩니다. 부동 소수점 숫자 , 부호있는 정수부호없는 정수에 대해 구문 분석 할 수있는 정확한 형식에 대한 자세한 정보를 찾을 수 있습니다 .

마지막으로 각 함수마다 std::wstring첫 번째 매개 변수로 a를 허용하는 과부하가 있습니다 .

숫자에서 문자열로

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

이것들은 더 간단합니다. 적절한 숫자 유형을 전달하면 문자열이 다시 나타납니다. 형식화 옵션의 경우 다른 답변에서 설명하는 것처럼 C ++ 03 stringsream 옵션으로 돌아가서 스트림 조작기를 사용해야합니다.

주석에서 언급했듯이 이러한 기능은 최대 정밀도가 아닌 기본 가수 정밀도로 돌아갑니다. 응용 프로그램에 더 많은 정밀도가 필요한 경우 다른 문자열 형식화 절차로 돌아가는 것이 가장 좋습니다.

이라는 이름의 비슷한 함수가 정의되어 있습니다.이 함수 to_wstring는을 반환합니다 std::wstring.


C ++ 03에서 숫자를 문자열로 변환하는 방법

  1. Do not use the itoa or itof functions because they are non-standard and therefore not portable.
  2. Use string streams

     #include <sstream>  //include this to use string streams
     #include <string> 
    
    int main()
    {    
        int number = 1234;
    
        std::ostringstream ostr; //output string stream
        ostr << number; //use the string stream just like cout,
        //except the stream prints not to stdout but to a string.
    
        std::string theNumberString = ostr.str(); //the str() function of the stream 
        //returns the string.
    
        //now  theNumberString is "1234"  
    }
    

    Note that you can use string streams also to convert floating-point numbers to string, and also to format the string as you wish, just like with cout

    std::ostringstream ostr;
    float f = 1.2;
    int i = 3;
    ostr << f << " + " i << " = " << f + i;   
    std::string s = ostr.str();
    //now s is "1.2 + 3 = 4.2" 
    

    You can use stream manipulators, such as std::endl, std::hex and functions std::setw(), std::setprecision() etc. with string streams in exactly the same manner as with cout

    Do not confuse std::ostringstream with std::ostrstream. The latter is deprecated

  3. Use boost lexical cast. If you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. To download and install boost and its documentation go here. Although boost isn't in C++ standard many libraries of boost get standardized eventually and boost is widely considered of the best C++ libraries.

    Lexical cast uses streams underneath, so basically this option is the same as the previous one, just less verbose.

    #include <boost/lexical_cast.hpp>
    #include <string>
    
    int main()
    {
       float f = 1.2;
       int i = 42;
       std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
       std::string si = boost::lexical_cast<std::string>(i); //sf is "42"
    }
    

How to convert a string to a number in C++03

  1. The most lightweight option, inherited from C, is the functions atoi (for integers (alphabetical to integer)) and atof (for floating-point values (alphabetical to float)). These functions take a C-style string as an argument (const char *) and therefore their usage may be considered a not exactly good C++ practice. cplusplus.com has easy-to-understand documentation on both atoi and atof including how they behave in case of bad input. However the link contains an error in that according to the standard if the input number is too large to fit in the target type, the behavior is undefined.

    #include <cstdlib> //the standard C library header
    #include <string>
    int main()
    {
        std::string si = "12";
        std::string sf = "1.2";
        int i = atoi(si.c_str()); //the c_str() function "converts" 
        double f = atof(sf.c_str()); //std::string to const char*
    }
    
  2. Use string streams (this time input string stream, istringstream). Again, istringstream is used just like cin. Again, do not confuse istringstream with istrstream. The latter is deprecated.

    #include <sstream>
    #include <string>
    int main()
    {
       std::string inputString = "1234 12.3 44";
       std::istringstream istr(inputString);
       int i1, i2;
       float f;
       istr >> i1 >> f >> i2;
       //i1 is 1234, f is 12.3, i2 is 44  
    }
    
  3. Use boost lexical cast.

    #include <boost/lexical_cast.hpp>
    #include <string>
    
    int main()
    {
       std::string sf = "42.2"; 
       std::string si = "42";
       float f = boost::lexical_cast<float>(sf); //f is 42.2
       int i = boost::lexical_cast<int>(si);  //i is 42
    }       
    

    In case of a bad input, lexical_cast throws an exception of type boost::bad_lexical_cast


In C++17, new functions std::to_chars and std::from_chars are introduced in header charconv.

std::to_chars is locale-independent, non-allocating, and non-throwing.

Only a small subset of formatting policies used by other libraries (such as std::sprintf) is provided.

From std::to_chars, same for std::from_chars.

The guarantee that std::from_chars can recover every floating-point value formatted by to_chars exactly is only provided if both functions are from the same implementation

 // See en.cppreference.com for more information, including format control.
#include <cstdio>
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <charconv>

using Type =  /* Any fundamental type */ ;
std::size_t buffer_size = /* ... */ ;

[[noreturn]] void report_and_exit(int ret, const char *output) noexcept 
{
    std::printf("%s\n", output);
    std::exit(ret);
}
void check(const std::errc &ec) noexcept
{
    if (ec ==  std::errc::value_too_large)
        report_and_exit(1, "Failed");
}
int main() {
    char buffer[buffer_size];        
    Type val_to_be_converted, result_of_converted_back;

    auto result1 = std::to_chars(buffer, buffer + buffer_size,  val_to_be_converted);
    check(result1.ec);
    *result1.ptr = '\0';

    auto result2 = std::from_chars(buffer, result1.ptr, result_of_converted_back);
    check(result2.ec);

    assert(val_to_be_converted == result_of_converted_back);
    report_and_exit(0, buffer);
}

Although it's not fully implemented by compilers, it definitely will be implemented.


I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:

// make_string
class make_string {
public:
  template <typename T>
  make_string& operator<<( T const & val ) {
    buffer_ << val;
    return *this;
  }
  operator std::string() const {
    return buffer_.str();
  }
private:
  std::ostringstream buffer_;
};

And then you use it as;

string str = make_string() << 6 << 8 << "hello";

Quite nifty!

Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number; (and its not as clever as the last one either)

// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
  std::stringstream buf;
  buf << str;
  RETURN_TYPE val;
  buf >> val;
  return val;
}

Use as:

int x = parse_string<int>("78");

You might also want versions for wstrings.

참고URL : https://stackoverflow.com/questions/5290089/how-to-convert-a-number-to-string-and-vice-versa-in-c

반응형