views:

102

answers:

4
while(true)
{ 
  cout << "Name: ";
  getline(cin, Name);
  if(Name == "Stop")
    break;

  cout << "Additional Name - Y/N: ";
  getline(cin, additional);
  if (additional == "Y") 
    cout << "Additional Name: ";
  getline(cin, Name2);
  else
    cout << "Location: ";
  getline(cin, Location);
  if(Location == "Stop")
    break;
}

chief.cpp: In member function ‘void BookList::Fill()’:

chief.cpp:128: error: ‘else’ without a previous ‘if’

After the user enters the first name, I would like to give the option to enter a second name. If "N" just skip down to Location, if "Y" go to Name2 and then on to Location.

+5  A: 

You have to enclose the statements between the if and the else within brackets { ... }.

Diego Sevilla
+4  A: 

You need to add braces here:

if (additional == "Y") 
     cout << "Additional Name: ";
      getline(cin, Name2);
else
     cout << "Location: ";
     getline(cin, Location);

Try:

if (additional == "Y") 
{
     cout << "Additional Name: ";
     getline(cin, Name2);
}
// You could have an else here, but that would make location only happen if "additional" was not "Y"

 cout << "Location: ";
 getline(cin, Location);

I suspect that you always want the following lines (getting location) to occur, so in this case, no else is required.

Reed Copsey
A: 

You need to enclose the body of if in braces to get rid of the error. By the looks of it you also need to enclose the else body in braces:

if (additional == "Y") {
  cout << "Additional Name: ";
  getline(cin, Name2);
 } else {
  cout << "Location: ";
  getline(cin, Location);
 }
codaddict
A: 

You may only discard the braces ({ and }) around blocks when the block contains exactly one statement (something ending with a semicolon (;)) or another statement with a block (if, for, while, etc).

For example, you can do this:

while (true)
    if (foo) {
        printf("Hello, ");
        printf("world\n");
    }

or even

while (true)
    if (foo)
        for (i = 0; i < 10; i++) {
            printf("Hello, ");
            printf("World!\n");
        }

But in your code, you need to use braces since your if statement contains two statements before the else statement. Therefore the if statement end after the cout line.

The end result should thus look something like this:

if (additional == "Y") {
   cout << "Additional Name: ";
   getline(cin, Name2);
}
else {
   cout << "Location: ";
   getline(cin, Location);
}
Mikael S