표준용량 구체화하십시오 int 로 변환할 수 있습니까?

그냥 투명지에 신속시작 질문이예요 # 39, ve 인터넷을 중심으로 생각하고 i& 상당히 비트 및 I& # 39, 그들 중 아무도 일한 적이 몇 번 com/downloads/global/corporate/iar/esg_prosupport. 솔루션은 물론 아직 밝혀지지 않았다. 내가 볼 때, t 짓궂군요 ASCII 코드 변환 충족되었으며 int 문자열으로 don& # 39.

우리는 방정식에 대한 간략한 개요 문자열로 통과시켰다. 우리가 이 문제를 제대로 break it down, 형식 및 선형 방정식. # 39 m, 할 수 없는 것을 말하고, 이번에는 두 I& 문자열으로 변환하시겠습니까 충족되었으며 int.

구체화하십시오 될 것으로 알고 있는 형식 (5) 또는 (25) 등 그러하매 it& # 39 의 말해둘꼐요 하지만 어떻게 문자열으로? 에서 푸십시오 충족되었으며 int.

제 생각에 대해 한 가지 방법은 실행하는지 / while 루프를 통해 모든 자리 숫자가 확인할지 구체화하십시오, 그 후, 추출 후 주요 & # 39, & # 39 - look to see if there was a int 가 있는 경우, 곱합니다, - 1.

이러한 복잡한 문제를 조금 넘는 작은 어쨌든요 보인다 아무 생각 없어?

질문에 대한 의견 (14)
해결책

C++11 에서 몇 가지 새로운 기능이 좋은 변환하십시오 표준용량 구체화하십시오 '에서' 여러 유형:.

그래서 대신

atoi( str.c_str() )

사용할 수 있습니다.

std::stoi( str )

여기서 '할 수 있다' 는 '네' 표준용량 구체화하십시오 str.

모든 변종에서 가지 버전 번호: '긴 단거리 이착륙기 (string)', '부동 소수점 스토프 (string)', '더블 스트로트 (string)'. 참조 http://en.cppreference.com/w/cpp/string/basic_string/stol

해설 (4)
std::istringstream ss(thestring);
ss >> thevalue;

39, ll 확인하려는 오류 플래그를 완벽하게 you& 수정하십시오.

해설 (8)

트로이 함수를 사용하여 변환하십시오 구체화하십시오 정수.

string a = "25";

int b = atoi(a.c_str());

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

해설 (1)

가능한 옵션 다음과 같습니다.

1. 첫 번째 옵션은: 스카노프 ()

    #include 
    #include 

        int i;
        float f;
        double d;
        std::string str;

        // string -> integer
        if(sscanf(str.c_str(), "%d", &i) != 1)
            // error management

        // string -> float
        if(sscanf(str.c_str(), "%f", &f) != 1)
            // error management

        // string -> double  
        if(sscanf(str.c_str(), "%lf", &d) != 1)
            // error management

이 때문에, 스칸프 는 오류 (또한 표시하는 치피치크) 의 큰 충돌 없이 너버 제한값 &quot 필드이므로 수 있는 입력 데이터를 일부 버전의 libc&quot, 자세한 내용은 here여기서요).

2. 두 번째 옵션은: 표준용량 sto () *

    #include 
    #include 

        int i;
        float f;
        double d;
        std::string str;

        try {
            // string -> integer
            int i = std::stoi(s);

            // string -> float
            float f = std::stof(s);

            // string -> double  
            double d = std::stod(s);
        } catch (...) {
            // error management
        }   

이 솔루션은 파선-짧은 우아한 하지만 C++11 의 호환일 컴파일러에도 에서만 사용할 수 있습니다.

3. 세 번째가: 스트리엄스

    #include 
    #include 

        int i;
        float f;
        double d;
        std::string str;

        // string -> integer
        std::istringstream ( str ) >> i;

        // string -> float
        std::istringstream ( str ) >> f;

        // string -> double  
        std::istringstream ( str ) >> d;

        // error management ??

그러나 이 솔루션을 통해 구별하기 힘든 나쁜거라 입력입니다 (http://otl. here).

4. 네 번째 옵션은: # 39 의 boost& lexical_cast

    #include 
    #include 

        std::string str;

        try {
            int i = boost::lexical_cast( str.c_str());
            float f = boost::lexical_cast( str.c_str());
            double d = boost::lexical_cast( str.c_str());
            } catch( boost::bad_lexical_cast const& ) {
                // Error management
        }

그러나 이는 단지 래퍼, 보다 나은 오류 관리 및 documentation 제안됩니다 스트림 스트럼 사용할 수 있다 (자세한 내용은 here).

5. 5 옵션: 스트라토 () *

이 솔루션은 오류로 인한 관리, 이는 매우 긴, 설명됨 삽입하십시오. 일반 없으므로 함수는 (int, 변환 요구되는가) 의 경우, 정수 (http://otl. here 이 변환 방식에 대해 달성할 수 있다).

6. 6 옵션: Qt

    #include 
    #include 

        bool ok;
        std::string;

        int i = QString::fromStdString(str).toInt(&ok);
        if (!ok)
            // Error management

        float f = QString::fromStdString(str).toFloat(&ok);
        if (!ok)
            // Error management 

        double d = QString::fromStdString(str).toDouble(&ok);
        if (!ok)
    // Error management     
    • 결론

C++11 총정리한, 최적의 솔루션이라는 표준용량 스토리 () 또는, 그 두 번째 옵션은 사용, qt 라이브러리를. 다른 모든 솔루션은 언제나 또는 갈레라 컴퍼니.

해설 (4)

무슨 얘기 [Boost.Lexical_cast] (http://www.boost.org/doc/libs/release/doc/html/boost_lexical_cast.html)?

다음은 그 예:

&gt. 다음 예제에서는) 에서는 명령행을 인수만 시퀀스로 숫자 데이터:

int main(int argc, char * argv[])
{
    using boost::lexical_cast;
    using boost::bad_lexical_cast;

    std::vector args;

    while(*++argv)
    {
        try
        {
            args.push_back(lexical_cast(*argv));
        }
        catch(bad_lexical_cast &)
        {
            args.push_back(0);
        }
    }
    ...
}
해설 (1)

알듯, 나의 모든 것, t # 39 wouldn& 솔루션을 사용할 수 있는 텍스트를 입력으로부터 양의 정수를 대응시키는 푸십시오 제외어 정수, 기초적 성질. It '사용' numeric_only 로케일에:


int main() {
        int num;
        std::cin.imbue(std::locale(std::locale(), new numeric_only()));
        while ( std::cin >> num)
             std::cout 
해설 (0)

39 의 it& 조금 있지만, 아마도 오버킬

(테스트링) ',' boost::lexical_cast&lt int&gt 작업에 대한 합니다. 아주 잘.

해설 (2)

'는' 트로이 정수로 변환하는 기능을 문자열으로 내장현 않았다고 가정하고 시작하는 문자열을 정수 표현.

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

해설 (1)

Http://www.cplusplus.com/reference/string/stoi/ 에서


// stoi example
#include    // std::cout
#include      // std::string, std::stoi

int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";

  std::string::size_type sz;   // alias of size_t

  int i_dec = std::stoi (str_dec,&sz);
  int i_hex = std::stoi (str_hex,nullptr,16);
  int i_bin = std::stoi (str_bin,nullptr,2);
  int i_auto = std::stoi (str_auto,nullptr,0);

  std::cout 
해설 (0)

Windows 에서 사용할 수 있습니다.


const std::wstring hex = L"0x13";
const std::wstring dec = L"19";

int ret;
if (StrToIntEx(hex.c_str(), STIF_SUPPORT_HEX, &ret)) {
    std::cout 
해설 (0)

뭐, 많은 답변, 많은 가능성. 내가 다른 c++컴파일러는 변환하는 방법을 누각되었습니다 슬라이드에서는 일부 통합 문자열으로 핵심 유형 (파선-짧은, int, long, 부울.). I came up with 정보정의다음 해결책:

#include
#include
#include
#include

using namespace std;

template
T toIntegralType(const string &str) {
    static_assert(is_integral::value, "Integral type required.");
    T ret;
    stringstream ss(str);
    ss >> ret;
    if ( to_string(ret) != str)
        throw invalid_argument("Can't convert " + str);
    return ret;
}

다음은 용례:

string str = "123";
int x = toIntegralType(str); // x = 123

str = "123a";
x = toIntegralType(str); // throws exception, because "123a" is not int

str = "1";
bool y = toIntegralType(str); // y is true
str = "0";
y = toIntegralType(str); // y is false
str = "00";
y = toIntegralType(str); // throws exception

스트라이스트림 출력입니다 변환할지 연산자입니다 문자열으로 중요한 유형) 에 사용하는 것은 어떻습니까? 다음은 대답:

39 의 말하도다 let& 문자열으로 고안되었습니다 대한 제한을 초과하는 값이 포함되어 있습니다 핵심 유형:. Int 는 최대 64 에 대한 이스마일 벽도스 2147483647.

39 의 let& 문자열으로 할당 값을 최대 int + 1: string str = 2147483648 &quot ";).

이제 변환할 때 구체화하십시오 충족되었으며 int:

stringstream ss(str);
int x;
ss >> x;

2147483647, x 가 지정하십시오. 말해둘꼐요 오류가 발생했습니다. 문자열이어야 &quot &quot. 2147483648. int (2147483647) 로 변환하지는 돼 있지 않았다. 이러한 오류는 투안테그라티파 제공된 함수은 별색에 외친 뒤 예외가 아니다.

해설 (0)
ll toll(string a){
    ll ret=0;
    bool minus=false;
    for(auto i:a){
        if(i=='-'){ minus=true; continue; }
        ret*=10;
        ret+=(i-'0');
    } if(minus) ret*=-1;
    return ret;
    # ll is defined as, #define ll long long int
    # usage: ll a = toll(string("-1234"));
}
해설 (0)

한 줄로 버전: '긴 n = 스트라토르 (s.c_str (), NULL, 베이스),'.

('s' 는 문자열, '기본' 은 'int' 등 2, 8, 10, 16.)

[이 링크] 참조할 수 있습니다 (https://stackoverflow.com/a/14794138/8328786) 에 대한 자세한 내용은 '스트라토르'.

핵심 사용할 수 있다는 ['스트라토르'] (http://www.cplusplus.com/reference/cstdlib/strtol/) ',' 코스타드리브 함수은 포함되어 있음.

이후 스트라토르 '만' 을 (를) ',' 문자열 처리 '를' 필요하다 '어레이입니다 챨 변환하십시오 챨' 어레이입니다. [이 링크] 참조할 수 있습니다 (https://stackoverflow.com/a/13294114/8328786).

예:


#include 
#include    // string type
#include    // bitset type used in the output

int main(){
    s = "1111000001011010";
    long t = strtol(s.c_str(), NULL, 2); // 2 is the base which parse the string

    cout 
해설 (0)

내 코드:


#include 
using namespace std;

int main()
{
    string s="32";  //String
    int n=stoi(s);  //Convert to int
    cout 
해설 (0)

쉽게 또 있다. # 39, & # 39 4& 있다고 가정해 봅시다 ',' 같은 문자 c = 1 단계에 따라서 할 수 있습니다.

제 1: int q

c 'q = (int); (q) 는 현재 52 표 (ascii). q = q 48. ascii 코드로 자리 바로 그 점에 대한 추가 48tb. '

두 번째 방법은.

39 'q = c-& 0& # 39;;; # 39, & # 39, 0& 같은 문자 '는 48

해설 (2)