我使用的书中的练习练习(重新阅读各种循环章节)指示我创建一个程序,不断要求用户输入单个字符。有两种规格:
这是我的代码:
// Takes character input, tallies periods, stops on dollar sign
#include <iostream>
using namespace std;
int main() {
char i; // input received
int j = 0; // counter for # of periods
cout << "This program will accept single-character entries and report the number of periods you've entered.\n";
for (;;) {
do {
cout << "Please enter a single character, using $ to stop: ";
cin >> i;
if(i == '.')
j++;
} while(i != '$');
if(i == '$')
cout << "Total number of periods entered is " << j << " .";
break;
}
return 0;
}
该程序运行正常,代码看起来很有效,请纠正我,如果我错了。对我来说似乎很奇怪的是在大多数代码中使用无限循环{}循环。本章使用了一两次,所以这是我目前知道以这种方式制作循环函数的唯一方法。
也许这只是我对该语言的经验不足,但是是使用带有(;;)
的循环,这在C ++中经常出现?有一个循环的语法没有定义的参数似乎对我需要做的事情有意义,但是(;;){}块的整体对我来说仍然很奇怪。
答案 0 :(得分:4)
在内循环之后不需要外循环或if
检查。
我还会在阅读时检查错误或EOF,因此会将其编码为:
int periods;
char ch;
std::cout << "Please enter a single character, using $ to stop: ";
for (periods = 0; std::cin >> ch && ch != '$'; )
{
if (ch == '.')
periods++;
std::cout << "Please enter a single character, using $ to stop: ";
}
std::cout << "Total number of periods entered is " << periods << " .";
答案 1 :(得分:1)
使用for (;;)
或其他类似while (1)
的内容我几乎只在书籍或示例代码段中看到过。虽然我从未在完整的程序中看到这一点,但它可能只是不那么常见。但是,通常,循环中至少有一个表达式(有时更多)。虽然只能使用breaks
,但它会降低可读性。请考虑以下事项:
for (;;){
// do some stuff here
if (anexpression) break;
}
和
do {
// do some stuff here
} while (anexpression);
哪一个更具可读性?我更喜欢后者,但它仍然只是一个意见。还有许多其他方法来编写循环(即):
evaluateinput:
if (anexpression) goto evaluateinput;
答案 2 :(得分:1)
Forever循环在电子产品上更常见。有时甚至看起来像这样:
void main()
{
Init();
while (1);
}
在这种情况下,main函数等待处理中断。
通常我们不会使用永久循环,但这不是一个错误的决定,只是不能用来解决问题的方法。
让我们说代码看起来:
while (1)
{
...
if (condition)
break;
}
我们可以改为:
while (!condition)
{
...
}
如果我们需要至少运行一次循环,我们可以使用do-while循环。