I'm Confused and it's only my second program :/

When i run my program, it's suppose to say Good if you write your name correctly and meant to repeat itself if you didn't, for some reason it always say Good even though you wrote your name incorrectly. If you guys can, can you tell me how to fix the problem.

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

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int main ()
{
	loop:
	string name;
	string yes;
	string no;
std::cout << "What is your name?\n";
std::getline (std::cin,name);
cout << "Are you sure it is " << name << "?" << endl;
loop2:
if (cin >> yes)
          {
           cout << "Good!";
          }
else if (cin >> no)
          {
          cout << "\nSo,";
          goto loop;
          }
else
          {
	cout << "please type yes or no";
	goto loop2;
          } 
system("PAUSE");
return 0;
}
1) do not use goto where it could easily be replaced with control structures.
2) What do you think happens on lines 16 and 20?
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
37
38
39
40
#include <iostream>
#include <string>

int main ()
{
    std::string name;

    read_the_users_name: // ask the user to enter the name
    {
        std::cout << "What is your name? ";
        std::getline( std::cin, name );

        check_if_the_name_is_correct : // ask the user if it was entered correctly
        {
            const std::string yes = "yes" ;
            const std::string no = "no" ;
            std::cout << "Are you sure it is " << name << "? " ;

            std::string answer ;
            std::getline( std::cin, answer ) ;

            if( answer == yes )
            {
                std::cout << "Good!\n" ;
            }

            else if( answer == no )
            {
                std::cout << "So, " ;
                goto read_the_users_name ; // ask the user to re-enter the name
            }

            else
            {
                std::cout << "please type yes or no\n" ;
                goto check_if_the_name_is_correct ; // ask for an yes ot no answer
            }
        }
    }
}


Now, try to replace the labels and gotos with control structures.

Does it make your code easier to read and understand?
Yes: Keep the changes and throw away the gotos
No: Roll back the changes and revert to the gotos
Okay, i'll try using Control Structures but 1 question, What does the word "const" do?, i'm curious as i usually skim through the C++ manual and miss out important code.
A const variable eg. a const std::string can't be modified after it has been initialized.
http://www.parashift.com/c++-faq-lite/const-and-type-safety.html
Topic archived. No new replies allowed.