passing table of floats as argument in c++ main

377 Views Asked by At

I have a c++ program, I would like the first argument of the main (argv[1]) to correspond to a table of float. Is it possible to do that??

I was thinking about putting in a string my floats separated with spaces (e.g. "1.12 3.23 4.32 1.1 ...") Is there a way to automatically convert such a string into a table of floats? If I understand well the atof function converts a string into a double. So it seems it could be possible to split my string using the spaces and then convert each portion using atof. This option does not seem to be very efficient to me? In addition it returns double and not float :(

So, is there a better way to pass table of float as argument of a c++ program ?

Thank you

4

There are 4 best solutions below

2
On

Save it in a text file, and then read it from the file when your program starts. I isn't worth it to pass it as a command-line argument.

0
On

The main() parameter list is as it is. You can pass the strings of your numbers as arguments to your program. The main function will have to parse its argument.

When you want to pass a space separated list of numbers in argv[1] you can use the strtok function to get the individual number strings and have to pass it to a conversion function.

When your conversion function returns a double you should check that the result can be represented by a float and cast the value to a float variable. But I would consider to use double as the internal representation.

0
On

A stringstream can do both the splitting at spaces and the parsing into a float.

std::stringstream ss(the_string);
std::vector<float> v(std::istream_iterator<float>(ss),
                     (std::istream_iterator<float>()));
                   // the extra parentheses here are ugly but necessary :(

How to obtain the string with the data depends on how large it is and where it is supposed to come from. Just keep in mind that in many systems the arguments passed to program are already split by spaces, putting each part in a different element of argv.

0
On

In addition to Singer's answer: The commandline should be used mainly by human, not computer. If you really need a table of values, use configuration file. You can always use human readable format for it.