c++学习笔记——杂记

字符串的输入
  1. cin(不存在吃掉前一个回车的情况)
    cin使用空格、制表符和换行符来确定字符串的结束位置。
    会出现以下问题
    遇到空格终止输入,不能得到完整的一行

    #include<iostream>
    using namespace std;
    const int Maxn = 20;
    int main()
    {
    	char name[Maxn];
    	cin >> name;
    	cout << name;
    	return 0;
    }
    
    In put:
    Li William
    Out put:
    Li
    
  2. get()与getline()
    两个函数都读取一行,直到遇到换行符结束。
    调用方法
    cin.get(arrayname,arraysize);
    cin.getline(arrayname,arraysize);
    cin.getline(arrayname1,arraysize2).getline(arrayname1,arraysize2);
    cin.get(arrayname1,arraysize2).get().get(arrayname1,arraysize2);
    区别
    getline()丢弃换行符,get()则保留
    比如cin.get(name1,size1).get(name2,size2)只会出现第一次调用的结果,第二次调用时看到的是第一次调用保留的换行。cin.getline(name1,size1).getline(name2,size2)两次调用都能正常进行。
    会出现以下问题

    #include<iostream>
    using namespace std;
    const int Maxn = 20;
    int main()
    {
    	int a;
    	char name[20];
    	cin >> a;
    	/*可以在这加cin.get()吸收回车*/
    	//cin.get(name, 20);
    	cin.getline(name,20);
    	cout << name;
    	return 0;
    }
    
    输入一个数字后程序直接结束
    
引用与指针的联系

引用对指针进行了简单封装,底层仍然是指针。

	int num = 108;
	int& rel_num = num;
	rel_num = 118;
	cout << &num << '\t' << &rel_num << endl;
	/*
	*与该引用等价的指针
    */
	/*int* rel_num = &num;
	*rel_num = 118;
	cout << &num << '\t' << rel_num << endl;*/
常量指针:
const int *p = &a;
指针的指向可以修改,
指针指向的值不可以修改。
指针常量:
int * const p = &a;
指针的指向不能改,
指针指向的值可以改。
const既修饰指针,又修饰常量:
指针的指向和指针指向的值都不能改。
new与delete

注意以下几点

  1. 用new来分配内存的通用格式:
    typeName * pointer_name = new typeName	
    
  2. 一定要配对的使用new与delete,附则会发生内存泄漏。
  3. 不要用使用delete来释放不是new分配的内存
  4. 不要使用delete释放偶同一块内存两次
  5. 如果使用new[ ]为数组分配内存,则应使用delete[ ]释放
    int* pter = new int[3];
    pter[0] = 1;
    pter[1] = 2; 
    pter[2] = 3;
    for (int i = 0; i < 3; i++) {
    	cout << *(pter + i) << endl;
    }
    delete[] pter;
    
  6. 如果使用new[ ]为一个实体分配内存,则应使用delete[ ]释放
    int* pter_a = new int;
    delete pter_a;
    
  7. 对空指针应用delete是安全的
  8. 使用new来创立动态结构
    注意:如果结构标识符是结构名,则使用句点运算符;如果标识符是指向结构的指针,则使用箭头运算符。pter->name = (*pter).name
    #include<iostream>
    #include<cstdio>
    using namespace std;
    const int Maxn = 20;
    struct node
    {
    	char name[20];
    	float volume;
    	double price;
    
    };
    int main()
    {
    	node* pter = new node;
    	cin.getline(pter->name, 20);
    	//等价于cin.getline((*pter).name,20),即pter->name = (*pter).name
    	cin >> pter->price;
    	cin >> pter->volume;
    	cout << pter->name << endl;
    	cout << pter->price << endl;
    	cout << pter->volume << endl;
    	delete pter;
    	return 0;
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值