I have a program which inputs multiple string and numeric variables from the command line. As I want to convert few inputs to numeric types, I have been using std::stringstream
as suggested at learncpp . Presently, my code looks something like:
main.cpp
int main(int argc, char* argv[]) {
if (argc != 7)
{
std::cout << "Execute the program in the following format:\n";
std::cout << ".\segment inputImage outputDir color k sigma minSize\n";
std::cout << "Exiting program\n";
std::exit(1);
}
float gaussianBlur, kValue;
int minimumComponentSize;
std::filesystem::path path = std::filesystem::u8path(argv[1]);
std::string outputFolder = argv[2];
std::string color = argv[3];
std::stringstream convert{argv[4]};
if (!(convert >> gaussianBlur))
{
gaussianBlur = 1.5; // default value
}
std::stringstream convertK{argv[5]};
if (!(convertK >> kValue))
{
kValue = 900; // default value
}
std::stringstream convertMin{argv[6]};
if (!(convertMin >> minimumComponentSize))
{
minimumComponentSize = 900;
}
....
As you can see, I'm creating a stringstream
variable for each argument that I want to convert to a numeric type. I can't re-assign another value to stringstream
variables. Is there a way to convert all the arguments from a single stringstream
? Is there a better way to do this?
You can write the required argv
values into a single stringstream
(separated by spaces), then read each out into the corresponding variables:
//...
std::stringstream convert;
convert << argv[4] << " " << argv[5] << " " argv[6]; // Add more "argv" strings
convert >> gaussianBlur >> kValue >> minimumComponentSize; // Read more values
//...
But, of course, error conditions are then a bit trickier to check for; if you need this, you can read the items from that (single) stringstream
one at a time, as you already do:
if (!(convert >> gaussianBlur))
{
gaussianBlur = 1.5; // default value
}
if (!(convert >> kValue))
{
kValue = 900; // default value
}
if (!(convert >> minimumComponentSize))
{
minimumComponentSize = 900;
}
To reassign a different value to the same std::stringstream
you'll need to clear it:
convert.str(std::string());
Now it's clerared an you can reuse it with a different value.
You must also call convert.clear();
to reset all the previously seted flags.
To add all the arguments to the same std::stringstream
@AdrianMole's answer .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.