4-4. while循环

  1. 格式:
statement1 while(test-expr) statement2 statement3

  1. 举例:
int i = 0; while(i < 10) { cout<< i << endl; i++; } cout<<"after while"<

  1. 执行顺序
Created with Rapha?l 2.2.0 statement1 test_expr statement2 statement3 yes no
#include #include #include using namespace std; int main(int argc, char* argv[]) { //while(test_condition) body //for(init_expr; test_expr; update){ statement } /*************************举例1*************************/ //读取字符串中的每一个字符 string s = "hellow world"; unsigned long size = s.size(); int i = -1; while((++i) < size) { if (s[i] != ' ') { cout << "<" << s[i] << ">"; } else { cout << s[i]; } //i++; 最好先编写控制变量值的代码 } cout << endl; /*************************举例2*************************/ string ss = "I love you "; auto p = begin(ss)-1; auto endp = end(ss); while ((++p) != endp) { if (*p != ' ') { cout << "<" << *p << ">"; } else { cout << *p; } //p++; 最好先编写控制变量值的代码 } return 0; }

    推荐阅读