字符串用双引号表示,如 “S”为字符串,它有两个字符’S’和’\0’(\0自动添加,实际上就是0x00)。“S”实际上就是字符‘S’的地址
// 以下都是字符串
// '\0'是字符串结束的标志
const char* cstr = "abc"; // 'a', 'b', 'c', '\0'
char charr1[4] = "abc"; // 'a', 'b', 'c', '\0'
char ch[] = "abc"; // 'a', 'b', 'c', '\0'
char ch[10] = {'a', 'b', '\0'};// 以下是字符数组
char ch[4] = {'a', 'b', 'c', 'd'};
cin
从输入缓冲区读取字符,默认以 空格、enter、tab结束
cin.getline(ch, 4)
读取一行(行尾为’\n’),然后清空输入缓冲区,将’\n’替换成’\0’
或者读取到第三个字符后+‘\0’停止读取,清空输入缓冲区中读取的字符
cin.get(ch, 4)
与getline相似,读取一行(以’\n’结尾)但是不将输入缓冲区中的’\n’清除,所以cin.get(xx,xx); cin.get(xxx,xx);会导致第二个get失效,一般cin.get(xx, xx).get();
cin.get() 可跳过换行符
混合输入字符串和数字
const int n = 10;char arr[n];char arr2[n];int y;cin >> y; // 添加cin.get()// cin不会将输入缓冲区中的换行符清空// getline看到换行符后认为输入结束cin.getline(arr, n);cout << y << arr;
用string
显示原始字符
cout << R"(Ji "King" "\n" instead of endl.)" << '\n';
// Ji "King" "\n" instead of endl.
// cout << R"任意字符("(yes'?)", sy.括号内为原始字符)同前" << '\n';
cout << R"+*(括号内为原始字符,不存在转义的情况)+*" << '\n';
类或者结构是对其实例化后对象的属性或方法的描述,因此一般不会在定义类或结构时对成员赋值。定义是描述性的语句,此时赋值是没有道理的。
在C++中列表初始化是一种较为通用的初始化方法(=是可选项,如果{}内没有东西则编译器会默认置零,不允许缩窄转换),可对结构体、普通变量等进行初始化。
结构体可在函数外部定义也可在函数内部定义。
可在结构中定义位字段
struct torgle_register
{unsigned int SN : 4; // 4 bits for SN valueunsigned int : 4; // 4 bits unusedbool goodIn : 1; // valid input(1 bit)bool goodTorgle : 1; // successful torgling
};
short tell[10]; // tell an array of 20 bytes
cout << tell; // displays &(tell[0])
cout << &tell; // displays address of whole array
从数字上说这两个值完全一样;但从概念上说,&tell[0](即tell)是一个2字节内存块的地址,而&tell是一个20字节内存块的地址。因此,表达式tell+1将地址值加2,而表达式&tell+1将地址值加20。换句话说tell的类型为(short*),而&tell的类型为short(*)[10]。即为
short (*pas)[10] = &tell; // pas points to array of 20 shorts// pas相当于二级指针其类型为 short (*)[10]
// 两种表示基本等价
pw[1] *(pw + 1)
数组的动态联编和静态联编
int a[常量或常量表达式];int size;
cin >> size;
int* arr = new int[size];
...
delete [] arr;
指针和字符串
char flower[10] = "rose;
cout << flower << "s are red\n";
C++数类型分为基本类型和复合类型。
基本类型分为整形和浮点型,复合类型如数组、指针、结构体等。