错误覆盖int到字符串C
Error coverting int to string 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;
相关文章:
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 构造<int>具有 2 个字符串文字的向量
- 字符串中int的加法运算
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- cin >> int 给定一个字符串将 int 赋值为 0
- 将字符串中的 int 转换为字母;
- 使用 switch,但我想用字符串而不是 int 进行选择
- 两个数组,int 和 string,如何显示带有对应 int 的字符串?
- 从字符串流中读取具有特定字段宽度的 int
- win 表单应用程序字符串^ 到 int
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 将字符串转换为 int 后的随机值
- 如何检查字符串是否正确以将其转换为 int?
- 在 c++ 中逐个字符从字符串传递到 int 时不精确
- <int> 使用 fmt 库将向量转换为字符串
- 我正在尝试将 int 值插入字符串,而不是 1,我得到 10
- 为什么编译:字符串 = int
- C++ 隐式类型转换字符串 -> int?
- 如何在C++中连接字符串+int+字符串