空语句:最简单的语句,空语句只有一个单独的分号。当程序中在语法上需要一条语句但是逻辑上却不需要时,此时应该使用空语句。
//不断的读取输入流的内容,直到输入中遇到s。
while (cin >> a && a != s)
; //使用空语句时,应该加上注释,使得代码阅读者知道语句是有意义的。
块(也称复合语句)是指用花括号括起来的(可能为空的)语句和声明序列。
当语言需要一个语句而程序逻辑需要多个语句时,可能会使用一个块。例如:
while (val <= 10)
{
sum += val;
++val;
}
#include
int main()
{
int sum = 0, val = 1;
while (val <= 10)
sum += val, ++val;
std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
// 改写之后的代码可读性降低了
return 0;
}
(a) while (string::iterator iter != s.end()) { /* . . . */ }
// iter变量未初始化,且初始化应该在while外部,修改:
std::string::iterator iter = s.begin();
while (string::iterator iter != s.end()) { /* . . . */ }
(b) while (bool status = find(word)) { /* . . . */ }
if (!status) { /* . . . */ }
// status声明在while的控制结构里,只能在while循环内部使用,if语句不在while块中,所以status应该在外部声明
// 赋值运算作为条件,通常应该加上括号。如果像这题这样没加,当find(word)返回false赋值给status时,循环将一直持续下去,修改:
bool status;
while ((status = find(word))) {/* ... */}
if (!status) {/* ... */}
#include
#include
#include
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::cin;
int main()
{
vector scores = {"F", "D", "C", "B", "A", "A++"};
int grade{0};
while (cin >> grade) {
string lettergrade;
if (grade < 60)
lettergrade = scores[0];
else {
lettergrade = scores[(grade - 50) / 10];
if (grade != 100) {
if (grade % 10 > 7)
lettergrade += "+";
else if (grade % 10 < 3)
lettergrade += "-";
}
}
cout << lettergrade << endl;
}
return 0;
}
#include
#include
#include
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::cin;
int main()
{
vector scores = {"F", "D", "C", "B", "A", "A++"};
int grade{0};
while (cin >> grade) {
string lettergrade = grade < 60 ? scores[0] : scores[(grade - 50) / 10];
lettergrade +=
(grade == 100 || grade < 60)
? ""
: (grade % 10 > 7) ? "+" : (grade % 10 < 3) ? "-" : "";
cout << lettergrade << endl;
}
return 0;
}
(a) if (ival1 != ival2)
ival1 = ival2; // 少了分号
else ival1 = ival2 = 0;
(b) if (ival < minval)
{
minval = ival; // 少了花括号
occurs = 1;
}
(c) int val; // val定义要在外部,才能在两个if语句中都使用它
if (ival = get_value())
cout << "ival = " << ival << endl;
if (!ival)
cout << "ival = 0\n";
(d) if (ival == 0) // 判断相等的是==,不是赋值的=
ival = get_value();
一个口语术语,用来指如何处理嵌套的if语句,在c++中,else总是与其最近的尚未匹配的if相匹配。
#include
using std::cout;
using std::endl;
using std::cin;
int main()
{
unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
char ch;
while (cin >> ch) {
if (ch == 'a')
++aCnt;
else if (ch == 'e')
++eCnt;
else if (ch == 'i')
++iCnt;
else if (ch == 'o')
++oCnt;
else if (ch == 'u')
++uCnt;
}
cout << "Number of vowel a: \t" << aCnt << '\n' << "Number of vowel e: \t"
<< eCnt << '\n' << "Number of vowel i: \t" << iCnt << '\n'
<< "Number of vowel o: \t" << oCnt << '\n' << "Number of vowel u: \t"
<< uCnt << endl;
return 0;
}
#include
using std::cin;
using std::cout;
using std::endl;
int main()
{
unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
char ch;
while (cin >> ch) switch (ch) {
case 'a':
case 'A':
++aCnt;
break;
case 'e':
case 'E':
++eCnt;
break;
case 'i':
case 'I':
++iCnt;
break;
case 'o':
case 'O':
++oCnt;
break;
case 'u':
case 'U':
++uCnt;
break;
}
cout << "Number of vowel a(A): \t" << aCnt << '\n'
<< "Number of vowel e(E): \t" << eCnt << '\n'
<< "Number of vowel i(I): \t" << iCnt << '\n'
<< "Number of vowel o(O): \t" << oCnt << '\n'
<< "Number of vowel u(U): \t" << uCnt << endl;
return 0;
}
#include
using std::cin;
using std::cout;
using std::endl;
int main()
{
unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, spaceCnt = 0,
tabCnt = 0, newLineCnt = 0;
char ch;
while (cin >> std::noskipws >> ch) switch (ch) {
case 'a':
case 'A':
++aCnt;
break;
case 'e':
case 'E':
++eCnt;
break;
case 'i':
case 'I':
++iCnt;
break;
case 'o':
case 'O':
++oCnt;
break;
case 'u':
case 'U':
++uCnt;
break;
case ' ':
++spaceCnt;
break;
case '\t':
++tabCnt;
break;
case '\n':
++newLineCnt;
break;
}
cout << "Number of vowel a(A): \t" << aCnt << '\n'
<< "Number of vowel e(E): \t" << eCnt << '\n'
<< "Number of vowel i(I): \t" << iCnt << '\n'
<< "Number of vowel o(O): \t" << oCnt << '\n'
<< "Number of vowel u(U): \t" << uCnt << '\n' << "Number of space: \t"
<< spaceCnt << '\n' << "Number of tab char: \t" << tabCnt << '\n'
<< "Number of new line: \t" << newLineCnt << endl;
return 0;
}
#include
using std::cin;
using std::cout;
using std::endl;
int main()
{
unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, spaceCnt = 0,
tabCnt = 0, newLineCnt = 0, ffCnt = 0, flCnt = 0, fiCnt = 0;
char ch, prech = '\0';
while (cin >> std::noskipws >> ch) {
switch (ch) {
case 'a':
case 'A':
++aCnt;
break;
case 'e':
case 'E':
++eCnt;
break;
case 'i':
if (prech == 'f') ++fiCnt;
case 'I':
++iCnt;
break;
case 'o':
case 'O':
++oCnt;
break;
case 'u':
case 'U':
++uCnt;
break;
case ' ':
++spaceCnt;
break;
case '\t':
++tabCnt;
break;
case '\n':
++newLineCnt;
break;
case 'f':
if (prech == 'f') ++ffCnt;
break;
case 'l':
if (prech == 'f') ++flCnt;
break;
}
prech = ch;
}
cout << "Number of vowel a(A): \t" << aCnt << '\n'
<< "Number of vowel e(E): \t" << eCnt << '\n'
<< "Number of vowel i(I): \t" << iCnt << '\n'
<< "Number of vowel o(O): \t" << oCnt << '\n'
<< "Number of vowel u(U): \t" << uCnt << '\n' << "Number of space: \t"
<< spaceCnt << '\n' << "Number of tab char: \t" << tabCnt << '\n'
<< "Number of new line: \t" << newLineCnt << '\n' << "Number of ff: \t"
<< ffCnt << '\n' << "Number of fl: \t" << flCnt << '\n'
<< "Number of fi: \t" << fiCnt << endl;
return 0;
}
case关键字和它对应的值一起被称为case标签,case标签必须是整型常量表达式。
(a) // 应该有break语句
unsigned aCnt = 0, eCnt = 0, iouCnt = 0;
char ch = next_text();
switch (ch) {
case 'a': aCnt++; break;
case 'e': eCnt++; break;
default : iouCnt++; break;
}
(b) // 如果在某处一个带有初值的变量位于作用域之外,在另一处该变量位于作用域之内,则从前一处跳到后一处是非法行为
// 这里ix定义不可以放在switch作用域内
unsigned index = some_value();
int ix;
switch (index) {
case 1:
ix = get_value();
ivec[ ix ] = index;
break;
default:
ix = static_cast(ivec.size())-1;
ivec[ ix ] = index;
}
(c) // case标签语法错误
unsigned evenCnt = 0, oddCnt = 0;
int digit = get_num() % 10;
switch (digit) {
case 1: case 3: case 5: case 7: case 9:
oddcnt++;
break;
case 2: case 4: case 6: case 8: case 0:
evencnt++;
break;
}
(d) // case标签必须是一个常量表达式
const unsigned ival=512, jval=1024, kval=4096;
unsigned bufsize;
unsigned swt = get_bufCnt();
switch(swt) {
case ival:
bufsize = ival * sizeof(int);
break;
case jval:
bufsize = jval * sizeof(int);
break;
case kval:
bufsize = kval * sizeof(int);
break;
}
#include
#include
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
string pre_word, word, max_repeat_word;
int repeat_times = 0, max_repeat_times = 0;
while (cin >> word) {
if (word == pre_word) {
++repeat_times;
} else {
repeat_times = 1;
pre_word = word;
}
if (max_repeat_times < repeat_times) {
max_repeat_times = repeat_times;
max_repeat_word = pre_word;
}
}
if (max_repeat_times <= 1){
cout << "no word was repeated" << endl;
} else {
cout << "the word '" << max_repeat_word << "' occurred " << max_repeat_times << " times" << endl;
}
}
(a) // ix在for循环的语句头中定义,if语句在for循环的语句块外,所以ix时未定义的
int ix;
for (ix = 0; ix != sz; ++ix) { /* ... */ }
if (ix != sz)
(b) // for循环语句头中某些部分可以省略,但是分号不能省略
int ix;
for (; ix != sz; ++ix) { /* ... */ }
(c) // ix和sz同时加1,循环永远也结束不了
for (int ix = 0; ix != sz; ++ix) { /*...*/ }
// while循环
int i;
while ( cin >> i )
// ...
// 等同的for循环
for (int i = 0; cin >> i;)
// ...
// for循环
for (int i = 0; i != size; ++i)
// ...
// 等同的while循环
int i = 0;
while (i != size)
{
// ...
++i;
}
#include
#include
using std::cout;
using std::endl;
using std::vector;
int main()
{
vector vec1{0, 1, 1, 2};
vector vec2{0, 1, 1, 2, 3, 5, 8};
auto size = vec1.size() < vec2.size() ? vec1.size() : vec2.size();
for (decltype(vec1.size()) i = 0; i != size; ++i) {
if (vec1[i] != vec2[i]) {
cout << "false" << endl;
return 0;
}
}
cout << "true" << endl;
return 0;
}
(a) // 添加括号
do {
int v1, v2;
cout << "Please enter two numbers to sum:" ;
if (cin >> v1 >> v2)
cout << "Sum is: " << v1 + v2 << endl;
}while (cin);
(b) int ival;
do {
// . . .
} while (ival = get_response()); // 不应在此范围内声明
(c) int ival = get_response();
do {
ival = get_response(); // ival不应在此范围内声明
} while (ival);
#include
#include
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main()
{
string rsp;
do {
cout << " 输入两个字符串: ";
string str1, str2;
cin >> str1 >> str2;
cout << (str1 <= str2 ? str1 : str2) << " 比另一个小。 "
<< "\n\n"
<< " 再一次? 输入yes或者no: ";
cin >> rsp;
} while (!rsp.empty() && rsp[0] == 'y');
return 0;
}
#include
#include
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main()
{
string read, tmp;
while (cin >> read)
if (read == tmp)
break;
else
tmp = read;
if (cin.eof())
cout << "一个单词也没有重复." << endl;
else
cout << read << "连续出现两次." << endl;
return 0;
}
#include
using std::cin;
using std::cout;
using std::endl;
#include
using std::string;
int main() {
string curr, prev;
bool no_twice = false;
while (cin >> curr) {
if (!isupper(curr[0])) {
prev = "";
continue;
}
if (prev == curr) {
cout << curr << " 连续出现两次。" << endl;
no_twice = true;
break;
}
prev = curr;
}
if (!no_twice) cout << " 没有单词重复 " << endl;
}
for (int sz = get_size(); sz <=0; sz = get_size())
; // 空语句
#include
int main(void)
{
int a, b;
std::cin >> a >> b;
std::cout << static_cast(a) / b << std::endl;
return 0;
}
#include
#include
int main(void)
{
int a, b;
std::cin >> a >> b;
if (b == 0) throw std::runtime_error("divisor is 0");
std::cout << static_cast(a) / b << std::endl;
return 0;
}
#include
#include
using std::cin;
using std::cout;
using std::endl;
using std::runtime_error;
int main(void)
{
int a, b;
cout << "Input two integers: ";
while (cin >> a >> b) {
try {
if (b == 0) throw runtime_error("divisor is 0");
cout << static_cast(a) / b << endl;
cout << " 输入两个整数: ";
}
catch (runtime_error err) {
cout << err.what() ;
cout << "\n再试一次? 输入 y 或 n:" << endl;
char c;
cin >> c;
if (!cin || c == 'n')
break;
else
cout << " 输入两个整数: ";
}
}
return 0;
}