用户输入一行文本,循环回显每个字符。如果字符为句点,break结束循环。
程序计算空格数。当字符不为空格时,循环使用continue语句跳过计数部分,注意continue语句导致该程序跳过循环体的剩余部分,但不会跳过循环的更新表达式。
体会break和continue的用法
代码:
#include <iostream>
const int ArSize = 80;
int main()
{
using namespace std;
char line[ArSize];
int spaces = 0;
cout<<"Enter a line of text: \n";
cin.get(line, ArSize);
cout<<"Complete line:\n"<<line<<endl;
cout<<"Line through first period:\n";
for(int i=0; line[i]!='\0'; i++)
{
cout<<line[i];
if(line[i] == '.')
{
break;
}
if(line[i] != ' ')
{
continue;
}
spaces++;
}
cout<<"\n"<<spaces<<" spaces\n";
cout<<"Done.\n";
return 0;
}
运行结果:
Enter a line of text:
mhjerry likes C++. Ho, Ho!
Complete line:
mhjerry likes C++. Ho, Ho!
Line through first period:
mhjerry likes C++.
2 spaces
Done.
Press any key to continue