我正在处理这段代码,它接受一个数字字符串并用每个"数字"填充一个数组。的字符串。我遇到的问题是尝试将整数转换为字符串。我尝试使用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。
答案 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';
答案 1 :(得分:0)
好的,我根据每个人的建议修改了我的代码,最终处理了这样的转换:
string String = static_cast<ostringstream*>( &(ostringstream() << x) )->str();
cout << String << endl;