28.8k views
3 votes
Write a complete C++ program. Initialize a vector numbers variable. Use a while to read one double at a time from the user until there is no more user input. Each double should be stored in the vector numbers. After the while loop, use a for-each loop to print each number on its own line.

This is my code, I'm not sure why the result is not priting.
#include
#include
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main()
{
vector numbers;
cout <<"Please enter a number: " << endl;
double input;
while (cin >> input)
{
for (double x{0}; x {
numbers.push_back(input);
}
}
for (double n : numbers)
{
cout << "You enter the following numbers: "<< input << endl;
}
return 0;
}

User Davydotcom
by
7.0k points

1 Answer

5 votes

Final answer:

The student's C++ code contains logical errors inside the while loop and in the printing section of the for-each loop. The provided answer includes a corrected version of the program that stores user input in a vector and then prints each number on its own line.

Step-by-step explanation:

The code you've presented has a logical error inside the while loop. Instead of checking for more user input, it's trying to perform a for loop using a variable x with the condition x < input which doesn't serve the purpose of the program. You also have a mistake in your final for-each loop where you're printing the value of input instead of n. Here is the corrected version of your program:

#include <iostream>
#include <vector>

using namespace std;

int main() {
vector<double> numbers;
cout << "Please enter numbers (press Ctrl+D to end input): \\";
double input;
while (cin >> input) {
numbers.push_back(input);
}

for (double n : numbers) {
cout << n << '\\';
}

return 0;
}

Make sure to prompt the user correctly and then read and store each double value into the vector. After you've captured all input, use a for-each loop to iterate over the vector and print each number on its own line.

User Brasofilo
by
7.8k points