如何在不使用 to_string 或 stoi 的情况下将 int 转换为 C++11 中的字符串

How can I convert an int to a string in C++11 without using to_string or stoi?

本文关键字:int 情况下 转换 字符串 C++11 stoi string to      更新时间:2023-10-16

我知道这听起来很愚蠢,但我在Windows7上使用MinGW32,并且" to_string没有在这个范围内声明。这是一个实际的 GCC 错误,我已经按照这些说明进行操作,但它们不起作用。那么,如何在不使用 to_stringstoi 的情况下将 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);
}
相关文章: