C++输入cin模版代码以及const与指针的关系

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值