C+ + Tutorial: how to do input validation using while loops.

preview_player
Показать описание
I demonstrate how to perform input validation in C++ using a while loop. This is a tutorial for beginners introducing the topic as covered in our textbook.

In other words, we're going to check user input with a while loop.

2:18 ⇒ Theory
3:39 ⇒ Get to the code

Here's the basic algorithm:

Ask for some input
while the input is something we don't like:
Tell the user there something wrong
Ask for the input again

Continue on with the rest of the program

We'll cover the logic, write a sample program, and see what happens if you use if (bad) instead of while (good), a common mistake made by new students. Sample programs are written using Visual Studio 2022.

// Learn More //
C++ Playlist:

while loops:

// Consider supporting this channel in multiple ways
Bitcoin: 177wfkQwzXiC8o2whQMVpSyuWUs95krKYB
Рекомендации по теме
Комментарии
Автор

Thank you so much, Hank. I was ignorantly trapping my entire if/else if/else code inside the loop WITH the small part I needed looped... until I found your video. Can't tell you how relieved I am to get past this part. Appreciate the step by step instruction. Very easy to understand now!

jakedodge
Автор

i think it was a good example to show use of do while loop here

faizaniftikhar
Автор

Could we do something like this to save some memory or just save some lines of code? Or is this less efficient?

#include <iostream>
using namespace std;

int main()
{
int number = -1;

while (number <= 0)
{
cout << "Enter a positive number: ";
cin >> number;

if (number <= 0)
{
cout << "Input must be positive. Try again!\n";
}
}

cout << "The number you entered: " << number << "\n";

cin.ignore();
cin.get();
return 0;
}

sebastianviecco
visit shbcf.ru