Second iteration of function call not behaving...

Trying to relearn C++ and started with this simple program. Data capture works as expected the first time, but if I trigger the DO loop by answering "no" to the question, it won't let me enter data. I will post the program output below the code.

I tried clearing the variable but that didn't make a difference. I suspect there is an issue with the getline, but it works on the first iteration. I can't see it.

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;

string name;
string correct;

string getName()
{
	cout << "Please enter your name.\n";
	getline(cin, name);
	return name;
}

string verifyName()
{
	cout << "You entered " << name << " as your name.\nIs this correct? Please enter yes or no.\n";
	cin >> correct;
	return correct;
}

int main()
{
	getName();
	verifyName();

	do
		{
			cout << "Sorry about that! Let's try again!\n\n";
			getName();
			verifyName();
	} while (correct != "yes");

	cout << "Perfect, thanks!";
	return 0;
}


Program output:

Please enter your name.
The Dude
You entered The Dude as your name.
Is this correct? Please enter yes or no.
no
Sorry about that! Let's try again!

Please enter your name.
You entered as your name.
Is this correct? Please enter yes or no.
Your main problem is leaving the newline in the input stream when reading 'correct'. Maybe use getline instead so you consume the newline. Alternatively you could do a cin.ignore(999, '\n') after the cin >> correct.

Your program structure is bad, though. You shouldn't use global variables since they teach bad habits. Declare local variables, pass function parameters, accept return values:

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
#include <iostream>
#include <string>
using namespace std;

string getName() {
    cout << "Enter your name.\n";
    string name;
    getline(cin, name);
    return name;
}

bool verifyName(const string& name) {
    cout << "You entered " << name
         << " as your name.\nIs this correct? Enter yes or no.\n";
    string correct;
    getline(cin, correct);
    return correct == "yes";
}

int main() {
    string name = getName();
    while (!verifyName(name)) {
        cout << "Let's try again!\n\n";
        name = getName();
    }
    cout << "Perfect, thanks!\n";
}

Awesome! I am tracking almost everything you did. Few questions.

bool verifyName(const string& name) --- Why a const here and what does the & do?

Why are global variables bad?

Thanks again.
Topic archived. No new replies allowed.