Reputation: 3
I'm working on a C++ code, but I'm having some problems since I have never used this language before.
The structure of my project (.pro) file contains different .ccp files, including:
IOFile.cpp
: where the file name I want to change is;
CModel.cpp
: where there is the model of my project and, particularly, the parameter (float), chosen by user each time, that I would like to use for my file name.
So, for now the output name is something like: filename.txt, but I would like to rename it in order to obtain in somthing like filename_parameter.txt (for example: file_0.998.txt).
The void of my IOFile.cpp
is written like:
void IOFile::saveIntensityMap(const char* fileName, vector<float>* intensityMap)
{
std::ofstream file(fileName, std::fstream::out|std::fstream::trunc);
}
whereas the parameter (ray_factor) is initialized in the CModel.cpp
file:
ray_factor= 0.99f
So, how could I pass the ray_factor, that is in CModel
, to the IOfile
? And how can I write a filename that includes a string and a float?
Sorry for the silly question, but I can't find a solution.
Upvotes: 0
Views: 680
Reputation: 140540
This is not a silly question, and there's a ton of bad advice on this particular subject out there.
First, to get the ray_factor
into saveIntensityMap
, simply pass it as another argument:
void IOFile::saveIntensityMap(const char* fileName,
float ray_factor,
vector<float>* intensityMap)
{
...
}
Second, forget you ever heard of formatted iostreams output, it is enormously more trouble than it's worth. (This is the part where there's lots of bad advice on the 'net. I personally never use iostreams at all; I think the old-fashioned <stdio.h>
API is a much more ergonomic interface. Writing a floating-point number into a string with proper control over the output format is one of the things that iostreams are especially bad at.)
To construct the filename you want, use snprintf
to format the number and concatenation of std::string
objects to assemble the name, like this: (note that I am assuming the fileName
argument to saveIntensityMap
does not have the .txt
extension already - it will probably be easier to change that than to take the string apart and put it back together; C++ is not really very good at strings)
char ray_factor_buf[10];
snprintf(ray_factor_buf, sizeof ray_factor_buf, "%.2f", ray_factor);
string full_filename = fileName;
full_filename += "_";
full_filename += ray_factor_buf;
full_filename += ".txt";
std::ofstream file(full_filename, std::fstream::out|std::fstream::trunc);
If your C++ library has not yet been updated to C++11, that last line will need to be
std::ofstream file(full_filename.c_str(), std::fstream::out|std::fstream::trunc);
Upvotes: 2