我在字符串连接方面遇到问题。
std::deque<std::string> fileNamesVector;
double * res_array;
string *strarr;
size = fileNamesVector.size();
res_array = new double[size];
strarr = new string [size];
我需要在 res_array 后面附加 4 个空格,后跟 filenamevector。 我怎样才能做到这一点。
strarr[i] = res_array[i] + " " + fileNamesVector[i];
但是它给出了错误。说“exp 必须具有算术或枚举类型” 请帮忙。
最佳答案
在 C++ 中,double、char *
或 std::string
之间没有隐式转换。
res_array[i] + ""
正在尝试将 double 添加到 char *
,因此编译器尝试隐式转换,但不存在,因此它为您提供错误提示 operator+
需要数字类型。
您需要将 res_array[i]
显式转换为字符串。
// File: convert.h
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
The example above is from The C++ FAQ ,尽管有很多 stackoverflow 问题专门针对这个主题,但 TC++FAQ 值得真正为 OG 喝彩:)
或者对于 C++11,使用 std::to_string
strarr[i] = std::to_string(res_array[i]) + " " + fileNamesVector[i];
关于C++ 字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13770136/