开发者

if/else format within while loop

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 开发者_JAVA技巧‘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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜