dimanche 2 mai 2021

How to print a series of integers separated by space?

Let's take an input : 10 20 30 40 50
I want the output to print exactly as the input but the following code prints only 10 as output.

#include<iostream>

int main(){

std::cout<<" Please enter sequence of numbers separated by space"
         << " then press enter : ";

         int numbers;
         std::cin>>numbers;

         std::cout << numbers <<' ';
}

Reason I think is because the input operator '>>' takes 10 as input and leaves space in the input stream. For the next input cin finds whitespace and concludes that the input has ended. Hence, 10 as output.

Now If I input using a while loop the code prints exactly what I want it to.

 int numbers;
 while(std::cin>>numbers)

 std::cout << numbers <<' '; 

OUTPUT : 10 20 30 40 50

Why the input works fine using a while loop? Please explain what is exactly happening.

Edit 1: I know the title is somewhat misleading but I did not know how to summarize my doubt into a small title.

Edit 2 : Please do not downvote it . I'm learning on my own and I don't have anyone to ask questions to. I've already received 2 downvotes and I don't know what the implications are If I get banned from asking further questions. Thank you.

Aucun commentaire:

Enregistrer un commentaire