while循环是初始化和更新部分的for循环;它只是一个测试条件和主体:
while (test-condition) body
如果表达式计算结果为true,程序将执行正文中的语句。
以下代码显示了如何使用while循环读取用户输入。
#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 readn";
return 0;
}
上面的代码生成以下结果。
以下循环遍历字符串中的每个字符,并显示字符及其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;
}
上面的代码生成以下结果。
以下代码代码显示如何使用clock()和ctime头来创建延时循环。
#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 << "startingan";
clock_t start = clock();
while (clock() - start < delay ) // wait until time elapses
; // note the semicolon
cout << "done an";
return 0;
}
上面的代码生成以下结果。
以下代码使用一个循环,如果数组已满,或者输入非数字输入则终止该循环。
#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 valuen";
else
cout << total / i << " = average of " << i << "n";
return 0;
}
上面的代码生成以下结果。
do while循环与其他两个不同,因为它是一个退出条件循环。
如果条件评估为false,则循环终止;否则,开始执行和测试的新循环。
这样的循环总是执行至少一次。
以下是do while循环的语法:
do body while (test-expression);
主体部分可以是单个语句或大括号分隔的语句块。
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter numbers in the range 1-10 to find ";
cout << "my favorite numbern";
do
{
cin >> n; // execute body
} while (n != 7); // then test
cout << "Yes, 7 is my favorite.n" ;
return 0;
}
上面的代码生成以下结果。
C++ 指针 vs 数组 C++ 指针指针和数组是密切相关的。事实上,指针和数组在很多情况下是可以互换的。例如,一个指向数组开头的指...
C++ 关系运算符重载 C++ 重载运算符和重载函数C++ 语言支持各种关系运算符(、、 = 、 = 、 == 等等),它们可用于比较 C++ 内置...
C++ 类成员访问运算符 - 重载 C++ 重载运算符和重载函数类成员访问运算符( - )可以被重载,但它较为麻烦。它被定义用于为一个...
C++ do...while 循环 C++ 循环不像 for 和 while 循环,它们是在循环头部测试循环条件。do...while 循环是在循环的尾部检查它的...