0
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’

用户输入名字后,我想提供输入第二个名字的选项。如果“N”直接跳到位置,如果“Y”跳到 Name2,然后跳到 Location。

4

4 回答 4

5

您必须将括号内if的语句括起来... 。else{}

于 2010-10-22T19:24:15.780 回答
4

您需要在此处添加大括号:

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

尝试:

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

我怀疑您总是希望出现以下几行(获取位置),因此在这种情况下,不需要其他内容。

于 2010-10-22T19:24:58.660 回答
0

您需要将主体括if在大括号中以消除错误。从外观上看,您还需要将else主体括在大括号中:

if (additional == "Y") {
  cout << "Additional Name: ";
  getline(cin, Name2);
 } else {
  cout << "Location: ";
  getline(cin, Location);
 }
于 2010-10-22T19:26:11.387 回答
0

当块正好包含一个语句(以分号 ( ) 结尾的语句)或另一个带有块 ( , , 等)的语句时,您只能丢弃块周围的大括号 ({和)。};ifforwhile

例如,您可以这样做:

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

甚至

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

但是在您的代码中,您需要使用大括号,因为您的if语句在语句之前包含两个else语句。因此if语句在该cout行之后结束。

因此,最终结果应如下所示:

if (additional == "Y") {
   cout << "Additional Name: ";
   getline(cin, Name2);
}
else {
   cout << "Location: ";
   getline(cin, Location);
}
于 2010-10-22T19:26:38.343 回答