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?
CodePudding user response:
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;
}