2014-10-27 170 views
0

我正在嘗試使用stoi()string轉換爲int,但我得到的錯誤代碼爲error: ‘stoi’ was not declared in this scope。這是給定的代碼。stoi未在此範圍內聲明?

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string str1 = "45"; 
    std::string str2 = "3.14159"; 
    std::string str3 = "31337 with words"; 
    std::string str4 = "words and 2"; 

    int myint1 = std::stoi(str1); 
    int myint2 = std::stoi(str2); 
    int myint3 = std::stoi(str3); 
    // error: 'std::invalid_argument' 
    // int myint4 = std::stoi(str4); 

    std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n'; 
    std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n'; 
    std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n'; 
    //std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n'; 
} 
+1

您必須使用C++ 11兼容的libC++實現。 – 2014-10-27 15:51:01

回答

4

stoi是從C++ 11,你應該嘗試與atoi

+1

如果他有選擇,比'atoi'更好['strtol'](http://man7.org/linux/man-pages/man3/strtol.3.html),儘管這是C99庫。 – Deduplicator 2014-10-27 16:02:26