while循環(huán)是初始化和更新部分的for循環(huán);它只是一個(gè)測試條件和主體:
while (test-condition) body
如果表達(dá)式計(jì)算結(jié)果為true,程序?qū)?zhí)行正文中的語句。
以下代碼顯示了如何使用while循環(huán)讀取用戶輸入。
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0; // use basic input
cout << "Enter characters; enter # to quit:\n";
cin >> ch; // get a character
while (ch != "#") // test the character
{
cout << ch; // echo the character
++count; // count the character
cin >> ch; // get the next character
}
cout << endl << count << " characters read\n";
return 0;
}
上面的代碼生成以下結(jié)果。
以下循環(huán)遍歷字符串中的每個(gè)字符,并顯示字符及其ASCII代碼。
#include <iostream>
const int ArSize = 20;
int main()
{
using namespace std;
char name[ArSize];
cout << "Your first name, please: ";
cin >> name;
cout << "Here is your name, verticalized and ASCIIized:\n";
int i = 0; // start at beginning of string
while (name[i] != "\0") // process to end of string
{
cout << name[i] << ": " << int(name[i]) << endl;
i++;
}
return 0;
}
上面的代碼生成以下結(jié)果。
以下代碼代碼顯示如何使用clock()和ctime頭來創(chuàng)建延時(shí)循環(huán)。
#include <iostream>
#include <ctime> // for clock() function, clock_t type
int main()
{
using namespace std;
cout << "Enter the delay time, in seconds: ";
float secs;
cin >> secs;
clock_t delay = secs * CLOCKS_PER_SEC; // convert to clock ticks
cout << "starting\a\n";
clock_t start = clock();
while (clock() - start < delay ) // wait until time elapses
; // note the semicolon
cout << "done \a\n";
return 0;
}
上面的代碼生成以下結(jié)果。
以下代碼使用一個(gè)循環(huán),如果數(shù)組已滿,或者輸入非數(shù)字輸入則終止該循環(huán)。
#include <iostream>
using namespace std;
const int Max = 5;
int main()
{
double fish[Max];
cout << "You can enter up to " << Max
<< " numbers <q to terminate>.\n";
cout << "fish #1: ";
int i = 0;
while (i < Max && cin >> fish[i]) {
if (++i < Max)
cout << "#" << i+1 << ": ";
}
double total = 0.0;
for (int j = 0; j < i; j++)
total += fish[j];
if (i == 0)
cout << "No value\n";
else
cout << total / i << " = average of " << i << "\n";
return 0;
}
上面的代碼生成以下結(jié)果。
do while循環(huán)與其他兩個(gè)不同,因?yàn)樗且粋€(gè)退出條件循環(huán)。
如果條件評(píng)估為false,則循環(huán)終止;否則,開始執(zhí)行和測試的新循環(huán)。
這樣的循環(huán)總是執(zhí)行至少一次。
以下是do while循環(huán)的語法:
do body while (test-expression);
主體部分可以是單個(gè)語句或大括號(hào)分隔的語句塊。
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter numbers in the range 1-10 to find ";
cout << "my favorite number\n";
do
{
cin >> n; // execute body
} while (n != 7); // then test
cout << "Yes, 7 is my favorite.\n" ;
return 0;
}
上面的代碼生成以下結(jié)果。
更多建議: