+ 1
How to use cin inside while loop.
I need explanation how to use cin inside while loop and when do we need to use it.
5 Antworten
+ 5
1. You can't do that on sololearn.
2. Just add the cin inside the while loop, and the program will always wait you to write something.
Example:
int i;
do{
cin>>i
cout<<"num is smaller than 100";
}
while(i<100);
(Btw, idk if this code actually works.)
+ 4
Well, you use cin inside a while loop when you need the user to enter a value that will be used after that, in the same loop.
Everytime the loop runs, the user can chose something else. For example, calculating x*y.
You could do an while loop, and user asked to enter x and y(for how many times he want), and if he enters 0 for example, to exit the program.
+ 3
int ch = 0;
while(ch != -1) {
cin >> ch;
}
This loop will keep iterating until the user don't enter -1.
+ 1
It’s not only for here i need to know for my exam where to write
+ 1
● How to use `cin` inside a `while` loop?
int n;
// Repeat while input stream
// succeeds in reading input
while(cin >> n)
{
cout << n << endl;
}
// Loop until a certain condition is satisfied
while(true)
{
cin >> n;
// exit loop if input invalid or an
// I/O error occurs.
if(!cin.good()) break;
cout << n << endl;
}
● When do we need to use it?
We need it when we want to read input many times. Rather than writing `cin >> n; ten times for example, we can setup a loop to deal with the repetitive works.
We also use `cin`, in a loop to get values for array elements. In this case, we use the subscript operator [] to tell C++ which element is about to be assigned a value.
int i = 0, arr[5] {0};
// Repeat until all five array
// elements had been assigned a value
while(i < 5)
{
cin >> arr[i];
cout << arr[i] << " ";
i++;
}
NOTE: Use of input in a loop is not supported in SoloLearn.