while语句(C++)

重复执行语句,直到表达式计算为零。

while ( expression )
   statement

备注

expression 的测试在每次执行循环前发生;因此 while 循环执行零次或更多次。 表达式必须是整型、指针类型或包含明确的整型或指针类型转换的类类型。

中断导航回归在语句体中执行时,也可以中止while 循环。 请使用continue语句来结束当前迭代但不退出while循环。 继续 将控件传递给下一轮循环 while。

以下代码使用 while 循环从字符串中剪裁尾随下划线:

// while_statement.cpp

#include <string.h>
#include <stdio.h>
char *trim( char *szSource )
{
    char *pszEOS = 0;

    //  Set pointer to character before terminating NULL
    pszEOS = szSource + strlen( szSource ) - 1;

    //  iterate backwards until non '_' is found 
    while( (pszEOS >= szSource) && (*pszEOS == '_') )
        *pszEOS-- = '\0';

    return szSource;
}
int main()
{
    char szbuf[] = "12345_____";

    printf_s("\nBefore trim: %s", szbuf);
    printf_s("\nAfter trim: %s\n", trim(szbuf));
}

在循环顶部计算终止条件。 如果没有尾随下划线,循环不执行。

请参见

参考

迭代语句(C++)

C++关键字

do-while 语句 (C++)

对语句(C++)

基于范围的 for 语句 (C++)