C++ Primer Plus 第五章之知识梳理

1.逗号运算符花絮

cata = 17,240;
被解释为
(cata = 17),240;

cata = (17,240);
被解释为cata = 240;

2.for循环体里的字符串

#include<iostream>
#include<cstring>
//提供了strcmp()函数原型 
using namespace std;
int main(){
	char word[5]="?ate";
	for(char ch = 'a';strcmp(word,"mate");ch++)
	{
		cout<<word<<endl;
		word[0]=ch;
	}
	return 0;
} 
  1. strcmp()函数在cstring头文件中,相同返回false,不同返回true,所以可以不用strcmp(word,“mate”)!=0
  2. 字符实际上是整型,可以用递增或递减运算,如ch++

3.while循环

  • 当不是指定次数循环时,如word != “mate”;最好用while循环,而不是for循环
  • 用string类重载运算符!=当至少有个操作数为string对象,另一个操作数可以是string对象,也可以是c-风格字符串。word != “mate”;

4.循环体中的cin输入

  • cin将忽略空格和换行符。因此输入中的空格没有被回显,也没有被包括在计数内。
  • 发送给cin的输入被缓冲。这意味着只有用户按下回车键后,他输入的内容才会被发送给程序。
#include<iostream>
#include <stdio.h>
using namespace std;
int main(){
	int ch;
	int count =0;
	while((ch = cin.get())!= EOF){
		cout.put(char(ch));
		++count;
	}
	cout<<endl<<count<<"\n";
	return 0;
} 

刚开始报错error: ‘EOF’ was not declared in this scope,要文件的最开始加上#include <stdio.h>,因为EOF、stderr等都是在这个文件中定义的

5.二维数组

char * cities[Cities] = {
	"asdfad",
	"adfad",
	"fdfdf"
	};

从存储空间来说,指针数组更为经济

char cities[Cities][20] = {
	"asdfad",
	"adfad",
	"fdfdf"
	};

如果要修改其中的任何一个字符串,则二维数组是更好的选择

string cities[Cities] = {
	"asdfad",
	"adfad",
	"fdfdf"
	};

希望字符串是可修改的情况下,string类自动调整大小的特性将使这种办法比使用二维数组更为方便。

发布了9 篇原创文章 · 获赞 0 · 访问量 1699

猜你喜欢

转载自blog.csdn.net/weixin_46021869/article/details/104083328