如何在不使用 to_string 或 stoi 的情况下将 int 转换为 C++11 中的字符串
How can I convert an int to a string in C++11 without using to_string or stoi?
我知道这听起来很愚蠢,但我在Windows7上使用MinGW32,并且" to_string
没有在这个范围内声明。这是一个实际的 GCC 错误,我已经按照这些说明进行操作,但它们不起作用。那么,如何在不使用 to_string
或 stoi
的情况下将 int 转换为 C++11 中的字符串?(另外,我启用了-std=c++11
标志)。
它不是最快的方法,但你可以这样做:
#include <string>
#include <sstream>
#include <iostream>
template<typename ValueType>
std::string stringulate(ValueType v)
{
std::ostringstream oss;
oss << v;
return oss.str();
}
int main()
{
std::cout << ("string value: " + stringulate(5.98)) << 'n';
}
我想
以不同的方式回答:只需获得mingw-w64。
说真的,MinGW32 充满了问题,甚至不好笑:
- http://sourceforge.net/p/mingw/bugs/1578/
- http://sourceforge.net/p/mingw/mailman/message/23108552/
- wWinmain, Unicode, and Mingw
使用MinGW-w64,您可以免费获得:
- 支持 Windows Unicode 入口点 (
wmain
/wWinMain
) - 更好的 C99 支持
- 更好的 C++11 支持(正如您在问题中看到的!
- 大文件支持
- 支持 C++11 线程
- 支持 Windows 64 位
- 交叉编译!这样你就可以在你喜欢的平台上处理你的 Windows 应用程序。
您可以使用
stringstream
.
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
int num = 12345;
stringstream ss;
ss << num;
string str;
ss >> str;
cout << str << endl;
return 0;
}
你可以滚动自己的函数来做到这一点。
std::string convert_int_to_string (int x) {
if ( x < 0 )
return std::string("-") + convert_int_to_string(-x);
if ( x < 10 )
return std::string(1, x + '0');
return convert_int_to_string(x/10) + convert_int_to_string(x%10);
}
尽管以前的答案更好,但我想给你另一种可能性,在下一个旧学校代码之后实现 INT 到 STRING 方法:
#include <string>
std::string int2string(int value) {
char buffer[20]; // Max num of digits for 64 bit number
sprintf(buffer,"%d", value);
return std::string(buffer);
}
相关文章:
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- 在这种情况下,int**在C中是什么意思
- 如何在不返回 C++ 值的情况下退出 int 函数?
- 是否有可能在没有复制的情况下传递 std::vector<int> 作为参数来获得 std::vector<std::array<int, 3>>?
- 如何对 int 变量应用验证,使其仅接受整数数据,并且在任何其他数据的情况下不会出错?
- 无符号 int 与无符号长 两者都是 32 位,但我无法在不转换的情况下混合它们......为什么?
- 如何在没有参数的情况下实现返回双向链表大小的函数?int size() const.
- <int> 在不破坏堆栈的情况下获取 C++ 中的堆栈总和
- 为什么在这种情况下使用 int *arr = new int [number]
- 在 int 数组的情况下,新表达式可以"overflow"吗?
- 如何在不复制的情况下更新 std::unordered_map<std::string, std::vector> 中的向量<int>?
- 如何在不使用堆栈或数组的情况下从INT中提取每个数字?(C )
- 读取即将在没有同步的情况下同时增加的int是安全的吗?
- 在没有初始化列表的情况下,在c++的headerfile中为const int赋值
- 如何在<int>不重建数组的情况下将 vector<vector> 转换为 int**?
- 在 priority_queue 内部 pair<int、int> 的情况下决定优先级?
- 有没有什么方法可以在不丢失十进制值的情况下将浮点值转换为int值
- 为什么两种情况下的行为不同1.int i=1,2,3;和第二.int i;i=1,2,3;
- 开关情况下的字符和 int 有什么区别?
- 在这种情况下,静态 int 的值会发生变化吗?