Redo a statement when false ?

I'm very new to programming in general and so do not know much... I made this code in my spare time:
#include <string>
using namespace std;

int main(){

string username;
string password;

cout<<"Enter username:"<<" ";
cin>>username;

if(username.length()<4){
cout<<"username must be atleast 4 characters long..."<<endl;
}

else{
cout<<"Enter password:"<<" ";
cin>>password;

if(password.length()<6){
cout<<"password must be atleast 6 characters long...";
}
else{
cout<<"signup successful";
}
}
return 0;
}

the code works completely, my question is what do I have to do to make the code stsrt over when the length of the username or password is less than required ? do I have to use a loop or something?
Hi,

you can use something like this:

1
2
3
4
5
6
7
8
9
10
11
while (true){
  cout<<"Enter username:"<<" ";
  cin>>username;

  if(username.length()<4){
    cout<<"username must be atleast 4 characters long..."<<endl;
  }
  else {
    break;
  }
}
Last edited on
Yeah, you need a loop. See below for one of doing it using a while loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string username;
	string password;
	bool succ_login = false;

	while (!succ_login)
	{
		cout << "Enter username: ";
		cin >> username;

		if (username.length() < 4)
		{
			cout << "username must be at least 4 characters long..." << endl;
			continue;
		}

		cout << "Enter password: ";
		cin >> password;
		if (password.length() < 6)
		{
			cout << "password must be at least 6 characters long..." << endl;
			continue;
		}

		succ_login = true;
		cout << "login successful" << endl;
	}

	return 0;
}
oh alright Thanks for the help
Topic archived. No new replies allowed.