while 循环中的 if/else 格式
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”则转到“名称2”,然后跳至“位置”。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须将
if
和else
之间的语句括在方括号{
...}
内。You have to enclose the statements between the
if
and theelse
within brackets{
...}
.您需要在此处添加大括号:
尝试:
我怀疑您总是希望出现以下几行(获取位置),因此在这种情况下,不需要其他内容。
You need to add braces here:
Try:
I suspect that you always want the following lines (getting location) to occur, so in this case, no else is required.
您需要将
if
的主体括在大括号中以消除错误。从外观上看,您还需要将else
主体括在大括号中: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 theelse
body in braces:仅当块仅包含一个语句(以分号 (
;
结尾的内容))时,才可以丢弃块周围的大括号({
和}
) ) 或另一个带有块的语句(if
、for
、while
等)。例如,您可以这样做:
甚至
但是在您的代码中,您需要使用大括号,因为您的
if
语句在else
语句之前包含两个语句。因此,if
语句在cout
行之后结束。最终结果应该是这样的:
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:
or even
But in your code, you need to use braces since your
if
statement contains two statements before theelse
statement. Therefore theif
statement end after thecout
line.The end result should thus look something like this: