C++处理输入异常
while (!(cin >> factor)) // bad input
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; Please enter a number: ";
}
数组处理函数的常用处理方式
修改数组:
void f_modify(double ar[], int n);
不修改数组:
void f_no_change(const ar[], int n);
此外还有另一种处理数组的方法,即指定元素区间(range),这个可以通过传递两个指针来完成:一个指针标识数组的开头,另一个指针标识数组的尾部。。例如C++标准模版库STL将区间方法广义化了,STL方法使用超尾的概念:即对于数组而言,标识数组结尾的参数将是指向最后一个元素后面的指针。
#include <iostream>
const int ArSize = 8;
int sum_arr(const int *begin, const int *end);
int main() {
using namespace std;
int cookies[ArSize] = {1, 2, 4, 8, 16, 32, 64, 128};
// some systems require preceding int with static to
// enable array initialization
int sum = sum_arr(cookies, cookies + ArSize);
cout << "Total cookies eaten: " << sum << endl;
sum = sum_arr(cookies, cookies + 3); // first 3 elements
cout << "First three eaters ate " << sum << " cookies.\n";
sum = sum_arr(cookies + 4, cookies + 8); // last 4 elements
cout << "Last four eaters ate " << sum << " cookies.\n";
return 0;
}
// return the sum of an integer array
int sum_arr(const int* begin, const int* end) {
const int* pt;
int total = 0;
for (pt = begin; pt != end; pt++) {
total += *pt;
}
return total;
}
指针与常量
int age = 29;
const int* pt = &age;
上述代码表面 pt
指向一个 const int
,因此不能用 pt 来修改这个值,即 *pt 的值为 const,不能修改,以下代码是无效的
*pt += 1;
cin >> *pt;
但是 age 变量是可以改变的, 即以下代码是有效的。
age = 20;
我们需要注意另外一种情况,这里可以用以下代码来说明:
int gorp = 16;
int chips = 12;
const int* p_snack = &gorp;
*p_snack = 20; // invaild
p_snack = &chips; // valid
int gorp = 16;
int chips = 12;
int const * p_snack = &gorp;
*p_snack = 20; // vaild
p_snack = &chips; // invalid
int gorp = 16;
int chips = 12;
const int const * p_snack = &gorp;
*p_snack = 20; // invaild
p_snack = &chips; // invalid
另外还要注意以下两种情况:
const float g_earth = 9.80;
const float* pe = &g_earth; // vaild
const float g_moon = 1.63;
float* pm = &g_moon; // invaild