Step by step analysis, for learning from the errors:
First there is no member function length()
for an array of characters, so you should define string m2="...";
in order for the code to compile.
Then unfortunately your code would print only one number: the last. Why ? Because your printf()
is outside the loop.
Once you've put it inside the loop, you'd have plenty of numbers, but more than you expect:
* the first iteration, it'd start with "1 23 45 6" => 1
* the second with " 23 45 6" => 23
* the third iteraton "23 45 6" => 23 again!
* the fourth iteration "3 45 6" => 3 (did you expect this ?)
So you'd have to jump from one number to the next. So instead of incrementing, you coud search for the next space, with function find_first_of()
:
for (int i = 0; i < m2.length(); i=m2.find_first_of(' ', i+1)) // jump to the next space
{
v2 = atof(&m2[i]);
printf("%.2f\n", v2);
}
Here the online demo.
Real c++ alternatives:
Have a look at πάντα ῥεῖ 's solution: that's the way we do it in C++