0

I would like to know how I can separate many numbers from a single string in the following way, or in another way but in a very short way:

void separate(string product)
{
    std::string orbits ("365.24 29.53 234.455");
    std::string::size_type sz;     // alias of size_t
    double earth = std::stod (orbits,&sz);
    double moon = std::stod (orbits.substr(sz));
    std::cout << "The moon completes " << (earth/moon) << " orbits per Earth year.\n";
}

output:

12,3684
KSIER45
  • 129
  • 1
  • 1
  • 6
  • Is that the actual output or the expected? Please provide both. – klutt Dec 07 '20 at 14:19
  • yiu can "split" using the space key as delimiter.... – ΦXocę 웃 Пepeúpa ツ Dec 07 '20 at 14:19
  • @klutt It is the real one, and it is only an example, I would like to do the same but with several numbers – KSIER45 Dec 07 '20 at 14:21
  • @ΦXocę웃Пepeúpaツ I want to use the shortest possible execution time and the least possible memory – KSIER45 Dec 07 '20 at 14:22
  • then define the numbers as `const double earth = 365.24;` etc.. Hardcoding the numbers as string is not going to save you any memory or performance – 463035818_is_not_an_ai Dec 07 '20 at 14:23
  • @KSIER45 But is it correct or not? Your question is unclear. – klutt Dec 07 '20 at 14:24
  • @largest_prime_is_463035818 it's fine but the input must be a string, I don't think I understood after using constant – KSIER45 Dec 07 '20 at 14:26
  • You have the advantage that simple code written in C++ will have reasonable performance by default. Of course, if you want additional performance you can get it. May I ask why you think you need this? Have you profiled and measured your code? – cigien Dec 07 '20 at 14:26
  • if the input string is always 3 numbers you can use a `istringstream` and formatted input via `>>`. – 463035818_is_not_an_ai Dec 07 '20 at 14:27
  • @klutt I explain that code that I have already done, it works to separate two numbers from a string, but if I put 5 numbers it will not work, what I would like is to make a function which separates and converts all the numbers that are in a string , to double variables and display those variables separated without using split – KSIER45 Dec 07 '20 at 14:29

0 Answers0