0

Hello I recently asked a question about separating n DOUBLE numbers and they deleted it because they say that it is a duplicate so in their answer they put a link to the "Answer" because that "Answer" is not working for me

How can I solve this error?

#include<iostream>
#include<sstream>
using namespace std;


void separate(string product)
{
    std::istringstream is(product);
    double n;
    int i = 0;
    while(is >> n)
    {
        cout << i << ": " << n << " ";
        i++;
    }
}
int main()
{
    string product1, product2;
    cin >> product1;
    separate(product1);
}

Input:

12 1 5.30

Output:

0: 12

I need the output to be:

0: 12 1: 1 2: 5.30
KSIER45
  • 129
  • 1
  • 1
  • 6
  • Note that your question was Closed, not Deleted. Can you add the line of code that calls the `separate` function as well? – cigien Dec 07 '20 at 15:44
  • 1
    The code you posted, when called as `separate("12 1 5.30")` [works for me](https://godbolt.org/z/Evhnaq) as you want. – KamilCuk Dec 07 '20 at 15:45
  • 1
    Vote to close as typo. Replace `cin >> product1;` with `std::getline(cin, product1);`. https://godbolt.org/z/qv45hM – Marek R Dec 07 '20 at 15:47
  • 1
    @MarekR That's not really a typo, that's a misunderstanding about how formatted input. works. – BoBTFish Dec 07 '20 at 15:48
  • `cin >> product1;` - `product1` is only `12`, not the whole line. – KamilCuk Dec 07 '20 at 15:51
  • Hopefully the duplicate question makes it clear now, but just to give you a simple answer: your `separate` code is fine, but `cin >> product1` only reads up to the first space, so you don't actually read multiple numbers to be able to split them up. – BoBTFish Dec 07 '20 at 15:51
  • @BoBTFish yes I know, but there is no vote to close as invalid use of API. Error is so simple that it doesn't deserve to be full answer. – Marek R Dec 07 '20 at 15:51
  • Please see the duplicate target, it addresses your issue. Also, I'm down-voting the question because I don't feel you have put in sufficient effort to ask this question. Please spend considerably more than an hour trying to solve your problem before posting a question. – cigien Dec 07 '20 at 15:51
  • @cigien In the answer of the duplicate they used a chain already created, and in my question I put that I wanted to introduce it, so the answer would not be completely complete regarding my question so I had to ask another – KSIER45 Dec 07 '20 at 15:57
  • To clarify, your question is well asked, and on-topic. You've shown an MCVE, input, output, and expected output. There's nothing wrong with the question itself. I'm just pointing out that you clearly learned this technique an hour ago, which means you've not spent sufficient time on trying to solve the problem yourself. – cigien Dec 07 '20 at 16:01
  • 1
    @cigien You are right and it will not happen again Thank you very much for the advice – KSIER45 Dec 07 '20 at 16:14

0 Answers0