2014-01-21 56 views
4

當我運行我的代碼,我得到在編譯時這個錯誤:無法轉換的字符/字符串爲int

# g++ -std=c++0x sixteen.cpp -O3 -Wall -g3 -o sixteen 
sixteen.cpp: In function ‘int main()’: 
sixteen.cpp:10: error: call of overloaded ‘stoi(char&)’ is ambiguous 
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2565: note: candidates are: int std::stoi(const std::string&, size_t*, int) <near match> 
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2626: note:     int std::stoi(const std::wstring&, size_t*, int) <near match> 

我擡頭的錯誤,隨後,關於這裏的其他問題也做了說明,但是我刪除using namespace std;後仍然會出現該錯誤。爲什麼這仍在發生,我能做些什麼來擺脫它?

代碼:

#include <iostream> 
#include <string> 

int main() { 
    std::string test = "Hello, world!"; 
    std::string one = "123"; 

    std::cout << "The 3rd index of the string is: " << test[3] << std::endl; 

    int num = std::stoi(one[2]); 
    printf("The 3rd number is: %d\n", num); 

    return 0; 
} 
+1

'std :: string'不能由單個'char'參數產生。 – chris

+0

'int num = std :: stoi(&one.c_str()[2]);'會工作,但只是因爲它是C字符串中的最後一個非NULL字符。 –

回答

9

std::stoi需要std::string作爲它的參數,但one[2]char

解決這個問題的最簡單的方法是使用數字字符都保證有連續值的事實,所以你可以這樣做:

int num = one[2] - '0'; 

或者,你可以提取數字作爲一個字符串:

int num = std::stoi(one.substr(2,1)); 

而另一種選擇,你可以使用,需要一個char和次數的構造函數,char應該出現構建std::string

int num = std::stoi(std::string(1, one[2])); 
+0

我總是會忘記那樣的事情。我一直在使用弱類型語言,現在有點太長了。謝謝! –

-1

你也可以使用在C++ 11中添加的std :: to_string。接受一個基本類型的參數,並返回一個字符串。

http://en.cppreference.com/w/cpp/string/basic_string/to_string

+0

再次閱讀:OP要字符串編號 – Paranaix

+0

他使用gcc 4.4.7。所以他需要更新他的gcc版本以支持C++ 11。 Gcc 4.4.7只在C++ 0x。 – jordsti

+0

@jordsti C++ 0x只是舊的,現在不鼓勵使用C++ 11的名稱,它們之間沒有區別。 gcc 4.4.7已經支持很多C++ 11,包括初始化列表:http://gcc.gnu.org/gcc-4.7/cxx0x_status.html – Paranaix