문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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.

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);
 }

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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top