错误覆盖int到字符串C



我正在处理此代码,该代码采用数字字符串,并用字符串的每个"数字"填充数组。我遇到的问题是试图将整数转换为字符串。我尝试使用to_string无济于事。

这是代码(请注意,这是从具有其他功能的较大程序中提取的):

#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。

,如用户4581301所述,您需要#include <string>来使用字符串函数。

以下是错误的:

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

atoi()可能会崩溃,因为c本身不是字符串,这意味着没有零件终结器。

您必须使用2个字符的缓冲区,并确保第二个字符是' 0'。这样的东西:

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

说,如果您的字符串为十进制(这是std::to_string()生成的),那么您不需要atoi()。相反,您可以使用减法来计算数字值(快得多):

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

好吧,我每个人的建议对我的代码进行了一些修改,最终以这样的方式处理转换:

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

最新更新