gpt4 book ai didi

C++ 字符串转换

转载 作者:搜寻专家 更新时间:2023-10-31 01:12:25 25 4
gpt4 key购买 nike

我在字符串连接方面遇到问题。

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 个空格,后跟文件名 vector 。我该怎么做。

strarr[i] = res_array[i] + "     " + fileNamesVector[i];

但是它给出了错误。说“exp 必须有算术或枚举类型”请帮忙。

最佳答案

在 C++ 中,double、char *std::string 之间没有隐式转换。

res_array[i] + "" 正在尝试向 char * 添加一个 double ,因此编译器会尝试进行隐式转换,但不存在,因此它会为您提供提示 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com