if / else格式在while循环中

时间:2010-10-22 19:21:14

标签: c++ block if-statement braces

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然后转到位置。

4 个答案:

答案 0 :(得分:5)

您必须将括号if中的else{之间的陈述} ... {{1}}括起来。

答案 1 :(得分: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);

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

答案 2 :(得分:0)

您需要将if的主体括在大括号中以消除错误。根据它的外观,你还需要将else主体括在大括号中:

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

答案 3 :(得分: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);
}