2012-08-03 110 views
0

我有一個字符串數組和一個整數數組。我想將字符串數組的元素轉換爲整數,然後將它們存儲在整數數組中。我寫了這個代碼:atoi和字符串數組

string yuzy[360]; 
int yuza[360]; 

for(int x = 0;x<360;x++) 
{ 
    if(yuzy[x].empty() == false) 
    { 

     yuza[x]=atoi(yuzy[x]); 
     cout<<yuza[x]<<endl; 
    } 
    else 
     continue; 
} 

這段代碼給出了這樣的錯誤: 錯誤:無法轉換 '的std :: string {又名性病:: basic_string的}' 到 '爲const char *' 的說法 '1' 'int atoi(con​​st char *)'

當我在atoi函數中寫入字符串(-75dbm)的內容時,它工作正常。但是當我寫(yuzy [x])時,我得到了錯誤。我怎樣才能讓atoi在字符串數組中很好地工作? 謝謝。

+1

只是一個建議,但堅持「-75dbm」確實有效,這不是非常好的做法。在轉換它們之前,嘗試對數字串進行一些清理。 – 2012-08-03 08:26:28

回答

7

atoi()需要C字符串(char指針)而不是C++字符串對象。使用

atoi(yuzy[x].c_str()); 

代替。

+0

這會導致錯誤:'error:'a.std :: basic_string <_CharT,_Traits,_Alloc> :: operator []中的成員'c_str'的請求,std :: allocator > (1u)',它是非類型'char' cout << atoi(a [1] .c_str())<< endl; – 2014-09-25 20:03:37

1

atoi接受C風格的字符串作爲parametter,所以,你可以使用atoi(yuzy[x].c_str());

3

作爲替代atoi,你可以使用std::stoi和相關的功能,如果你有C++ 11的支持。

yuza[x] = std::stoi(yuzy[x]);