Is there an equivalent to the “for … else” Python loop in C++?

前端 未结 14 2052
野的像风
野的像风 2021-01-31 01:21

Python has an interesting for statement which lets you specify an else clause.

In a construct like this one:

for i in foo:
  if         


        
14条回答
  •  礼貌的吻别
    2021-01-31 02:00

    I would accomplish this with a simple helper variable:

    #include 
    #include 
    
    int main()
    
    {
        bool b;
        printf("Numbers which are multiples of 7:\n");
    
        for (int i=8; b=(i<12); i++)
        {
            if (i%7==0)
            {
                printf("%d", i);
                break;
            }
        }
        if (!b)
        {
            printf("no numbers found\n");
        }
        return 0;
    }
    

    This way, you need to implement the condition (in the above examplei<12) only at one place.

提交回复
热议问题