Restarting a program

Hello, I am trying to figure out a way I can ask the user if they want to restart the program. I did it with a do while loop but when it loops back around it doesn't get any new information from the keyboard???
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main ()
{
    
    char again;
    do
    {
        char name[256];
        
        cout<<"Enter a name:  ";
        cin.getline (name,256);

        cout<<name;
        
        
        cout<<"Another (Y/N)?  ";
        cin>>again;
        
    }while ((again =='Y') || (again =='y'));
        
        
        return 0;
    };
    
You could use a simple goto.

Some people don't like it because in large amount of code it can easily become difficult to keep track of.

For this short amount it should be fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main ()
{
    
    char again;
    char name[256];
        
input:
        cout<<"Enter a name:  ";
        cin.getline (name,256);

        cout<<name;
        
        
        cout<<"Another (Y/N)?  ";
        cin>>again;
        
        if ((again =='Y') || (again =='y'))
        {
        goto input;
        }
        else cout << "Thank you please come again!";
}


Also I am assuming you are using

 
using namespace std;


You shouldn't be, you should put "std::" in on your own. The "using namespace std" is considered bad practice.
Last edited on
Thank you. This is actually for a larger program but the idea is the same... I tried to use the goto input in this and its still not letting me put in another name from the keyboard each time, it is just leaving the name blank?
Use this instead

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
	{

		char again;

	input:
		char name[256];
		std::cout << "Enter a name: \n";
		std::cin >> name;
		std::cout << name << "\n";


		std::cout << "Another (Y/N)? ";
		std::cin >> again;

		if ((again == 'Y') || (again == 'y'))
		{
			goto input;
		}
		else std::cout << "Thank you please come again!";
	}


The getline you were using was not working the second time because you used it after doing

cin >> again;

This wont work because there is something called a buffer that you would need to flush out before using getline again.

For something like this cin will work well enough.

Just so you know in the future this is how you would use the same code if you had to use getline for some arbitrary reason...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
	{

		char again;
		char name[256];

	input:
		cout << "Enter a name:  ";
		cin.getline(name, 256);

		cout << name << "\n";


		cout << "Another (Y/N)?  ";
		cin >> again;
		cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

		if ((again == 'Y') || (again == 'y'))
		{
			goto input;
		}
		else cout << "Thank you please come again!";
	}
Last edited on
Thank you Very much it works perfect!
Topic archived. No new replies allowed.