Break 语句不起作用
这个程序应该将 name 的字符数存储在变量 str_length 中(其中 name < 50 个字符以“.”结尾)我很困惑为什么这段代码只吐出第一个字符,这意味着它从循环中中断当 i = 0 时,对于诸如“Jonathan”之类的名字。难道它不应该解析字符串直到找到“.”,然后才从 for 循环中中断吗?
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string name;
int str_length;
cout << "What's your name" << endl;
cin >> name;
for (int i = 0; i < 50; i++)
{
cout << name[i];
if (name[i] == '.')
str_length = i;
break;
}
cout << endl;
system("PAUSE");
return 0;
}
This program should store the number of characters of name in the variable str_length (where name < 50 characters terminated by a ".") I'm baffled as to why this code only spits out the first character, meaning it breaks from the loop when i = 0, for a name such as "Jonathan." Shouldn't it parse through the string until it finds the ".", only then breaking from the for loop?
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string name;
int str_length;
cout << "What's your name" << endl;
cin >> name;
for (int i = 0; i < 50; i++)
{
cout << name[i];
if (name[i] == '.')
str_length = i;
break;
}
cout << endl;
system("PAUSE");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你有:
这实际上是:
你想要:
你在每个循环结束时
break
ing。You have:
Which is actually:
You want:
You are
break
ing at the end of each loop.您在
if
条件周围缺少{}
。所以break
是在没有任何条件的情况下执行的,因此循环在第一次迭代时退出。You are missing
{}
aroundif
condition. Sobreak
is executed without any condition, hence the loop is exited in the first iteration itself.这表明即使对于一行 if 语句也不使用大括号也是危险的。我怀疑你这样做了:
然后添加了
break
。如果你这样做了:在前面,在花括号内添加中断是很自然的,并且你不会遇到这个错误。
This demonstrates the danger of not using braces even for one line if statements. I suspect you did this:
and then added the
break
later. If you had done this:up front, it would have been natural to add the break inside the curly braces, and you wouldn't have had the bug.