C++ 常用函数讲解--本人遇到的

1、const修饰变量位置不同的区别

const (int) *p;   //const修饰*p,*p是指针指向的对象不可变

(int) const *p;  //const修饰*p,*p是指针指向的对象不可变

(int)*const p;   //const修饰p,p不可变,p指向的对象可变

const在*左边,则不变的是指针指向的对象,const在*右边,则指针指向本身不变,指向的对象的值可变。

const (int) *const p;  //前一个const修饰*p,后一个const修饰p,指针p和p指向的对象都不可变

const修饰离他最近的对象

1)  const char * p
2)  char * const p

 这里的 const 关键字是用于修饰常量,书上说 const 将修饰离它最近的对象,所以,以上两种声明的意思分别应该是:
1)  p 是一个指向常量字符的指针,不变的是 char 的值,即该字符的在定义时初始化后就不能再改变。
2)  p 是一个指向字符的常量指针,不变的是 p 的值,即该指针不能再指向别的。

Bjarne 在他的《The C++ Programming Language》里面给出过一个助记的方法——“以 * 分界,把一个声明从右向左读”。
注意语法,* 读作 pointer to (指向...的指针),const (常量) 是形容词,char (变量类型) 和 p (变量名) 当然都是名词。 
1)  const char * p 读作:p is a pointer to a const char,译:p 是一个指针(变量),它指向一个常量字符(const char)。
2)  char * const p 读作:p is a const pointer to a char,译:p 是一个常量指针(const p),它指向一个字符(变量)。

左定值,右定向

 const在*的左边不能改变字符串常量的值,

const在*的右边不能改变指针的指向

2、字符型和数值型转换

https://www.cnblogs.com/onycea/p/5400681.html

  • 字符型→浮点型(整型)

  • long strtol(const char *_String, char **_EndPtr, int _Radix);

    _Radix:表示进制,范围为2~36和0

    _EndPtr:指向字符串中不合法的部分

    说明:若_Radix为2,则‘0’、‘1’合法,若_Radix为10,则‘0’、‘1’……‘9’合法,若_Radix为16,则‘0’,‘1’……‘f’合法

#include <iostream>
using namespace std;
void main()
{
    long num_2, num_8, num_10, num_16;
    char str[20] = "1079";
    char *str1;
    num_2 = strtol(str, &str1, 10);    //    num_2是转化的结果long是整型的一种
    /*
	str :要转换的字符串,这个str即将被转换为数值型。
	str1 :str里面可能有不合法的字符,存到str1里面。
	第三个参数10:代表10进制,有效字符0~9
	返回值 num_2 :转换成数值型的值,这里都是整型。
	下面代码同理:
	*/
	cout << num_2+1 << endl;      //这里输出1080          
    cout << str1 << endl;                
    num_8 = strtol(str, &str1, 8);        // 8进制,107合法
    cout << num_8 << endl;                // 输出71,八进制107在十进制中为71
    cout << str1 << endl;                // 输出不合法的9aeg
    num_10 = strtol(str, &str1, 10);    // 10进制,1079合法
    cout << num_10 << endl;                // 输出1079
    cout << str1 << endl;                // 输出不合法的aef
    num_16 = strtol(str, &str1, 16);    // 十六进制,1079ae合法
    cout << num_16 << endl;                // 输出1079726,十六进制1079ae在十进制中为1079726
    cout << str1 << endl;                // 输出不合法的g
}

1. 将字符串转换为双精度浮点型值

double atof(const char *_String);

#include <iostream>
using namespace std;
void main()
{
    long num_2, num_8, num_10, num_16;
    char str[20] = "1079.1";
    char *str1;
	double res = atof(str);
	cout << res + 1<< endl; //输出为1080.1
}

2. 将字符串转换为双精度浮点型值,并报告不能被转换的所有剩余数字

double strtod(const char *_String, char **_EndPtr);

#include <iostream>
using namespace std;
void main()
{
    long num_2, num_8, num_10, num_16;
    char str[20] = "1079.1a";
    char *str1;//用来存放不合法的字符的
	double res = atof(str);
	double res1 = strtod(str, &str1); 
	cout << res + 1<< endl; //输出为1080.1
	cout << str1<< endl; //输出 a
}
  • 浮点型→字符型

猜你喜欢

转载自blog.csdn.net/weixin_42053726/article/details/88398662
今日推荐