-4

I need to load vector with infinite loop and to print it. Loading is over when 0 entered.

OUTPUT:

Enter numbers: 1 3 1 4 2 1 3 1 4 2 1 3 0
1 3 1 4 2 1 3 1 4 2 1 3

Code:

#include <iostream>
#include <vector>
int main()
{
    std::vector<double>vektor;
    double a;
    for(;;)
    {
      std::cout << "Enter numbers: ";
      std::cin>>a;
      if(a!=0)vektor.push_back(a);
      if(a==0)break;
    }
    for(double a:vektor)
    std::cout << a << " ";
    return 0;
}

I get this output:

Enter numbers: 1 3 1 4 2 1 3 1 4 2 1 3 0 
Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: Enter numbers: 1 3 1 4 2 1 3 1 4 2 1 3

Could you explain me why there are so many duplicates of string "Enter numbers: "? If I load numbers one by one I wouldn't get any duplicate, but I need to load them all in one line like in example output. How could I modify this code to do that?

Evg
  • 25,259
  • 5
  • 41
  • 83
  • 2
    learn to debug: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/995714), [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – phuclv Mar 12 '22 at 01:21
  • "Could you explain me why there are so many duplicates of string "Enter numbers" yes because you have `std:: cout << "enter numbers"` on every loop – pm100 Mar 12 '22 at 01:23
  • Reframing the question as "how does `cin` work on a line of stdin with spaces between the integers?" might help you search for the answer. – JohnFilleau Mar 12 '22 at 01:24
  • I thought for this I would need `std::cin.ignore()` or `std::cin.clear()` –  Mar 12 '22 at 01:26
  • not needed, just read your code, each time round that loop adds one number to the vector, it also prints that message, so you get that same number of messages as numbers added to the vector. Move the print message out of the loop – pm100 Mar 12 '22 at 01:34

1 Answers1

0

Could you explain me why there are so many duplicates of string "Enter numbers: "?

Because you are outputting Enter numbers on every loop iteration before reading a new number. Simply move that statement above the loop instead.

Also, your loop can be simplified. You are ignoring the error state of the stream after each >> call.

Try this:

#include <iostream>
#include <vector>

int main()
{
    std::vector<double>vektor;
    double a;

    std::cout << "Enter numbers: ";

    while(std::cin >> a && a != 0)
    {
      vektor.push_back(a);
    }

    for(double a: vektor)
        std::cout << a << " ";

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770