2017-03-02 33 views
-1

我正在處理此代碼,它需要一個數字字符串並用字符串的每個「數字」填充一個數組。我遇到的問題是嘗試將整數轉換爲字符串。我嘗試使用to_string無濟於事。將int轉換爲字符串C++的錯誤

#include <cstdlib> 
#include <stdlib.h> 
#include <iostream> 
#include <time.h> 
#include <typeinfo> 

    int fillarr(int &length) { 
     int arr[length]; 
     string test = "10010"; //test is an example of a numeric string 
     int x = 25 + (std::rand() % (10000 - 100 + 1)); 

     std::string xstr = std::to_string(x); //unable to resolve identifier to_string 
     cout << xstr << endl; 
     cout << typeid (xstr).name() << endl; //just used to verify type change 

     length = test.length(); //using var test to play with the function 
     int size = (int) length; 
     for (unsigned int i = 0; i < test.size(); i++) { 
      char c = test[i]; 
      cout << c << endl; 
      arr[int(i)] = atoi(&c); 

     } 
     return *arr; 
    } 

我怎麼能INT X轉換爲字符串:

這裏是代碼(注意,這是與其他功能的更大的程序拉)?我有這個錯誤:無法解析標識符to_string。

+0

可能的複製[在C++中將int轉換爲字符串的最簡單方法](http://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c)。你需要解釋'std :: to_string'出了什麼問題,而不僅僅是說「它沒有工作」。我們不能用一種明顯的方法來將'int'轉換爲'std :: string',從而在心理上調試你的問題。 – ShadowRanger

+0

我知道它是相似的,但我只是不知道爲什麼我看起來像一個嘗試和真正的方法的錯誤。我是C++的新手,所以任何提示都非常值得歡迎。 –

+0

代碼將不會編譯,並且我在代碼中留下了錯誤 –

回答

3

如用戶4581301所述,您需要使用字符串函數#include <string>

下,雖然是錯誤的:

arr[int(i)] = atoi(&c); 

atoi()將有可能崩潰,因爲c本身並不是一個字符串,意味着不會有任何空終止符。

你將不得不使用2個字符的緩衝區,並確保第二個是'\ 0'。類似的東西:

char buf[2]; 
buf[1] = '\0'; 
for(...) 
{ 
    buf[0] = test[i]; 
    ... 
} 

話雖這麼說,如果你的字符串是十進制(這是什麼std::to_string()產生),那麼你就不需要atoi()。相反,你可以使用減法(快得多)計算的數字值:

arr[int(i)] = c - '0'; 
+0

謝謝,很多好的建議在這裏 –

0

好吧,我修改了我的代碼每個建議一點,從每個人,結束了處理這樣的轉換:

string String = static_cast<ostringstream*>(&(ostringstream() << x))->str(); 
cout << String << endl;