开发者

Break statement not working

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 thi开发者_如何学运维s 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;  
 }


You have:

for (int i = 0; i < 50; i++)
{
    cout << name[i];
    if (name[i] == '.')
       str_length = i;
       break;         
}

Which is actually:

for (int i = 0; i < 50; i++)
{
    cout << name[i];

    if (name[i] == '.')
    {
       str_length = i;
    }

    break;         
}

You want:

for (int i = 0; i < 50; i++)
{
    cout << name[i];
    if (name[i] == '.')
    {
       str_length = i;
       break;  
    }       
}

You are breaking at the end of each loop.


You are missing {} around if condition. So break is executed without any condition, hence the loop is exited in the first iteration itself.


This demonstrates the danger of not using braces even for one line if statements. I suspect you did this:

 if (name[i] == '.')
    str_length = i;

and then added the break later. If you had done this:

 if (name[i] == '.') { 
    str_length = i;
 }

up front, it would have been natural to add the break inside the curly braces, and you wouldn't have had the bug.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜