I am doing my custom image file format to display images in CLI but i need to convert size_t
to std::string
:
namespace csfo {
class Res {
public:
char* BLANK_DATA = "...";
};
...
inline char* generate(int COLOR, size_t x, size_t y, bool verbose) {
csfo::Res RES;
...
std::string dimenssions[2] = {
std::to_string(x),
std::to_string(y)
};
std::string DATA = RES.BLANK_DATA;
DATA = DATA.replace(DATA.begin(), DATA.end(), "[X_SIZE]", dimenssions[0]);
...
};
...
}
But i get this error when i try to call std::to_string()
No instance of overloaded function matches the argument list c/c (304)
Can someone please help me? Thanks.
I except my code to work
CodePudding user response:
Your error means that your compiler didn't find any matching "variant" (overloading) of std::string::replace method.
To replace given text in std::string
, you should:
- Find the text position and determine the text length.
- Check if found.
- Replace if found.
E.g:
#include <iostream>
#include <string>
//! Replaces the first occurence of @param text in @param textTemplate with @param toInsert.
// Since C 17 use std::string_view for @param text.
void replace_text(std::string& textTemplate, const std::string& text, const std::string& toInsert)
{
const std::size_t pos = textTemplate.find(text);
if (pos == std::string::npos)
{
/// Given @param text not found.
return;
}
textTemplate.replace(pos, text.length(), toInsert);
}
int main()
{
static const std::string X_SIZE = "[X_SIZE]";
std::string DATA = "My data template with [X_SIZE] occurence.";
replace_text(DATA, X_SIZE, std::to_string(4));
std::cout << DATA << std::endl;
return 0;
}
The membercsfo::Res::BLANK_DATA
should be const char*
or std::string_view
or std::string
but not just char*
- because you cannot modify it when pointing to string literal.
CodePudding user response:
Reading between the lines of what you are trying to do I think this is the correct code
size_t n = DATA.find("[X_SIZE]"); // find where [X_SIZE] is in DATA
DATA.replace(n, n 8, dimenssions[0]); // and replace it with dimenssions[0]
There's no error checking in this code (i.e. what if [X_SIZE] is not found), and the hard coded constant 8
should be factored out (eight is the length of "[X_SIZE]").