c++ primer plus 笔记

 

贵在坚持 给自己加加油

 

C++新版中推荐#include<iostream.h>改成#include<iostream> using namespace std;

 

cin.get();防止程序运行完毕自动退出,或如codeblocks这类IDE默认运行console_runner 工具已经具备此功能,无侵入

\n endl 场合要注意

 

头文件climits是ANSI C头文件limits.h的C++版本

 

SIZEOF相关文章太多了

 

有符号无符号也一样 比如有无数算法相关优化

 

  
    
#include < iostream >
using namespace std;
int main()
{
// cout.setf(ios_base::fixed,ios_base::floatfield);
float num1 = 10 / 3.0 ;
double num2 = 10.0 / 3.0 ;
const float million = 1.0e6 ;
cout
<< " num1= " << num1 << endl;
cout
<< " million*num1= " << million * num1 << endl;
cout
<< endl;
/////////////////////////////////////////////
cout << " num2= " << num1 << endl;
cout
<< " million*num2= " ;
cout
<< million * num2 << endl;
return 0 ;
}
   

 

 

无cout.setf(ios_base::fixed,ios_base::floatfield);

num1=3.33333
million*num1=3.33333e+006

 

num2=3.33333
million*num2=3.33333e+006

否则

num1=3.333333
million*num1=3333333.250000

 

num2=3.333333
million*num2=3333333.333333

 

有的编译器无ios_base,可以改成ios::fixed和ios::floatfield。float有效位数是6

 

 

第四章 复合类型

 

1、int yams[3]    cout<<sizeof yams; //the values is 12bytes   cout<<sizeof yams[0];//the values is 4 bytes;

2、求数组元素个数:short things[]={1,5,3,8}; int num_elements=sizeof things/sizeof(short);
要去看看BOOST之类有没提供方便方法

3、cin使用空白(空格)、制表符和换行符来定字符串的边界,所以cin>>Alia Dive相当与只输入Alia

5、面向行的输入:cin.getline()和cin.get();getline()函数读取整行,它使用Enter键输入换行符来确定输入结尾,getline(name,20)有两个参数,一个是数组名,一个是个数;而cin.get()并不再读取且丢弃换行符,也可以有两个参数,cin.get(name,20).get()

6、cin.clear() 恢复输入;

 

第五章 循环和关系表达式

 

1、int x; cout<<(x=100)<<endl;   输出100;

2、假设x=100,则cout<<(x<3);输出0

3、假设x=100,cout.self(ios_base::boolalpha); cout<<(x<3); 输出false;

 

  
    

#include
< iostream >
using namespace std;
int main()
{
int x = 10 ;
cout
<< (x = 10 ) << endl; // 说明赋值语句显示其结果
cout << (x > 5 ) << endl; // 说明判断显示其bool值1或0
cout << (x < 2 ) << endl;
cout.setf(ios_base::boolalpha);
cout
<< (x > 5 ) << endl; // 说明设置显示格式后以字符串显示
cout << (x < 2 ) << endl;
/*
10
1
0
true
false
*/

return 0 ;
}


4、

  
    
int i = 10 ;
for ( int i = 0 ; i < 5 ; i ++ )
// 正确,注意for 后也没有 {}

 

5、strcmp比较字符串是否相等,返回bool类型 ex:char word[]="aate";strcmp(word,"mate")=1(不相等为1)

 

  
    
#include < iostream >
#include
< cstring >
using namespace std;
int main()
{
char word[ 5 ] = " ?ate " ;
for ( char ch = ' a ' ; strcmp(word, " mate " ); ch ++ )
{
cout
<< word << " \n " ;
word[
0 ] = ch;
}
cout
<< " After loop ends,word is:[ " << word << " ]\n " ;
return 0 ;
}

 

6、clock()函数(用在循环让程序等待就很费CPU了,考虑用WINAPI)

 

  
    
#include < ctime > 用clock_t 作为clock()的返回类型;
#include
< iostream >
using namespace std;
#include
< ctime >
int main()
{
cout
<< " Enter the delay time,in seconds: " ;
float secs;
cin
>> secs;
clock_t delay
= secs * CLOCKS_PER_SEC;
cout
<< " starting……\a\n " ;
clock_t start
= clock();
while (clock() - start < delay)
;
cout
<< " Done! " << " \n " ;

return 0 ;
}

 


7、cin的三种格式: ①原始的不会读取空格、换行符等;② cin.get(ch)读取输入中的下一个字符(即使是空格)用cin.get(ch)替代cin>>ch;

 

8、cin.get(name,Arsize).get() 相当于cin.get(name,Arsize);cin>>get();
ex:

 

  
    

#include
< iostream >
using namespace std;
int main()
{
char ch;
int counts = 0 ;
// cin>>ch;
cin. get (ch);
while (ch != ' # ' )
{
cout
<< ch;
counts
++ ;
// cin>>ch;
cin. get (ch);
}
cout
<< endl << counts << " characters read\n " ;
return 0 ;
}
/* 输出:
see ken run#really fast
seekenrun
9 characters read
Press any key to continue……
存在的问题:没有读取空格,下面用cin.get() 补救
*/


#include
< iostream >
using namespace std;
int main()
{
char ch;
int counts = 0 ;
cin.
get (ch);
while (ch != ' # ' )
{
cout
<< ch;
counts
++ ;
cin.
get (ch);
}
cout
<< endl << counts << " characters read\n " ;
return 0 ;
}

/* 输出:
see ken run#really fast
see ken run
11 characters read
Press any key to continue……
*/

 


9、Dos下可以用gofish.exe<fishtale.txt 把fishtale.txt文本值输入给gofish

 

10、检测文件尾eof,cin将两位eofbit和failbit都设置为1。如果检测到EOF,则cin.eof()将返回true,否则false,fail也是如此;可以按ctrl+z,enter来模拟文件尾结束条件(dos 、unix用ctrl+d结束)
ex1 :while((ch=cin.get())!=eof)
ex2 :while(!cin.fail()) //while inut has not failed
while(cin)或者while(cin.get(ch))可以检测其他失败原因;

 

  
    

#include
< iostream >
using namespace std;
int main()
{
char ch;
int counts = 0 ;
cin.
get (ch);
while (cin.fail() == false )
{
cout
<< ch;
counts
++ ;
cin.
get (ch);
}
cout
<< " \n " << counts << " characters read\n " ;
return 0 ;
}
/* 输出:
the green bird sings in the winter.<Enter>
the green bird sings in the winter.
yes,but the crow flies in the dawn.<Enter>
yes,but the crow flies in the dawn.
<ctrl><z>

72 characters read
Press any key to continue……
*/

 

 

11、cout.put(ch)来显示字符,相当于C语言中的putchar();

 

  
    
#include < iostream >
using namespace std;
int main( void )
{
char ch;
int counts = 0 ;
while ((ch = cin. get ()) != EOF)
{
cout.put(
char (ch));
counts
++ ;
}
cout
<< counts << " characters read\n " ;
return 0 ;
}
/* 输出
the sullen mackerel sulks in the shadowy shallows.<Enter>
the sullen mackerel sulks in the shadowy shallows.
yes,but the blue bird of happiness harbors secrets.<Enter>
yes,but the blue bird of happiness harbors secrets.
<ctrl><z>
103 characters read
Press any key to continue……
*/

 

第六章   分支语句和逻辑操作符

 

1、一些C++实现中,数组进行初始化,必须在数组声明中使用关键字static;

2、cctype字符函数库
#include<cctype>(老式为ctype.h)
ch是一个字母,isalpha(ch)返回非零值,否则返回0
ch是标点,ispunct(ch)返回true,这些函数的返回类型为int,而不是bool,但通常bool 转换允许将它们视为bool类型,区别if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))与if(isalpha(ch))效果是一样的,显然简单多了,而isdigit()测试字符是否为数字字符,ispunct(ch)测试字符是否为标点符号

 

  
    

#include
< iostream >
using namespace std;
#include
< cctype >
int main()
{
char ch;
int spaces = 0 ;
int digits = 0 ;
int puncts = 0 ;
int letter = 0 ;
int others = 0 ;
do
{
cin.
get (ch);
if (isspace(ch)) spaces ++ ;
else if (isdigit(ch)) digits ++ ;
else if (ispunct(ch)) puncts ++ ; // 计算标点符号
else if (isalpha(ch)) letter ++ ;
else others ++ ;
}
while (ch != ' @ ' );
cout
<< " spaces= " << spaces << endl;
cout
<< " digits= " << digits << endl;
cout
<< " puncts= " << puncts << endl;
cout
<< " letter= " << letter << endl;
cout
<< " others= " << others << endl;
return 0 ;
}

 


/*
输出:--------------------------
jody "java-java" joystone,noted restaurant critic,
celebrated her 39th birthday with a carafe of 1982
chateau panda.@
spaces=15
digits=6
puncts=7
letter=89
others=0
其中,spaces包括换行符、空格等*/

 

 

 


3、cctype中的字符函数
isalnum()
isalpha()
iscntrl()
isdigit()
isgraph()
islower()
isupper()
isprint()
ispunct()
isspace()
isxdigit()

 


tolower():如果是大写字母 则为返回其小写,否则返回该参数;
toupper():如果是小写字母 则为返回其大写,否则返回该参数。

4、将枚举量用作标签
ex: enum{red,orange,yellow,green,blue,violet,indigo};

 

  
    
// enum枚举
#include < iostream >
using namespace std;
enum {red,orange,yellow,green,blue,violet,indigo};
int main()
{
cout
<< " enter you color(0-6): " ;
int codes;
cin
>> codes;
while (codes >= red && codes <= indigo)
{
switch (codes)
{
case red:
cout
<< " ---red\n " ;
break ;
case orange:
cout
<< " ---orange\n " ;
break ;
case yellow:
cout
<< " ---yellow\n " ;
break ;
case green:
cout
<< " ---green\n " ;
break ;
case blue:
cout
<< " ---blue\n " ;
break ;
case violet:
cout
<< " ---violet\n " ;
break ;
case indigo:
cout
<< " ---indigo\n " ;
break ;
// default:cout<<"---error!\n";break;
}
cout
<< " enter you color(0-6): " ;
cin
>> codes;
}
return 0 ;
}

 

/*输出:
enter you color(0-6):1
---orange
enter you color(0-6):2
---yellow
enter you color(0-6):4
---blue
enter you color(0-6):6
---indigo
enter you color(0-6):3
---green
enter you color(0-6):5
---violet
enter you color(0-6):7
//退出
*/

 

5、break和continue语句

 

代码
   
     
// 跳转
#include < iostream >
using namespace std;
const int Arsize = 80 ;
int main()
{
char line[Arsize];
int spaces = 0 ;

cout
<< " enter the lines: " ;
cin.
get (line,Arsize);
for ( int i = 0 ; line[i] != ' \0 ' ; i ++ )
{
cout
<< line[i];
if (line[i] == ' . ' )
break ;
if (line[i] == ' ' )
{
spaces
++ ;
continue ;
}
}
cout
<< " \n " << spaces << " spaces\n " ;
cout
<< " Done.\n " ;

return 0 ;
}

 

/*
输出:----------------------------
enter the lines:let's do lunch today. you can pay!
let's do lunch today.
3 spaces
Done.
Press any key to continue……
---------------------------------------*/

 

6、读取数字的循环
①://计算求每天捕鱼的重量,

 

代码
   
     
#include < iostream >
using namespace std;
const int MAX = 5 ;
int main()
{
double fish[MAX];
cout
<< " please input the weight of your fish\n " ;
cout
<< " you may enter uo to " << MAX << " fish <q to terminate>.\n " ;
cout
<< " fish #1: " ;
int i = 0 ;
while (i < MAX && cin >> fish[i]) // 转化为BOOL型,当输入的不是数字,则该程序不再输入。
{
if ( ++ i < MAX)
cout
<< " fish # " << i + 1 << " : " ;
}
double total = 0.0 ;
for ( int j = 0 ; j < i; j ++ )
total
+= fish[j];
if (i == 0 )
cout
<< " No fish\n " ;
else
cout
<< total / i << " =average weight of " << i << " fish\n " ;
cout
<< " Done!\n " ;

return 0 ;
}

 

/*输出:------------------------
please input the weight of your fish
you may enter uo to 5 fish <q to terminate>.
fish #1: 30
fish #2:35
fish #3:25
fish #4:40
fish #5:q
32.5 =average weight of 4 fish
Done!
Press any key to continue
---------------------------------*/

 

②://当输入的不是数字的时候就继续输入的实现

 

代码
   
     
#include < iostream >
using namespace std;
const int MAX = 5 ;
int main()
{
int golf[MAX];
cout
<< " please enter you golf scores.\n " ;
cout
<< " you must enter " << MAX << " rounds.\n " ;
int i;
for (i = 0 ; i < MAX; i ++ )
{
cout
<< " round # " << i + 1 << " : " ;
while ( ! (cin >> golf[i])) // 当输入不是数字时重新输入
{
cin.clear();
// reset input
while (cin. get () != ' \n ' )
continue ;
cout
<< " please enter a number: " ;
}
}
double total = 0.0 ;
for ( int j = 0 ; j < MAX; j ++ )
total
+= golf[j];
cout
<< total / MAX << " =acerage score " << MAX << " score!\n " ;


return 0 ;
}

 


/*输出:-----------------------------
please enter you golf scores.
you must enter 5 rounds.
round #1: 88
round #2: 87
round #3: must i
please enter a number: 103
round #4: 94
round #5: 86
91.6 =acerage score 5 score!
Press any key to continue……
---------------------------------*/

 

第七章 函数——C++的编程模块

 

1、只有当函数有返回值时,才可以当函数用在赋值语句中;

2、用语接受传递值的变量被称为形参,传递给函数的值被称为实参;

3、cin.get()将读取所有的输入符号,包括空格和换行符,而cin>>则跳过空格和换行符;

4、函数如何使用指针来处理数组 sum_arr(int arr[],int n)等价于sum_arr(int *arr,int n);

5、大多数情况下,C/C++都将数组名视为指针 arr[i]==*(ar+i),&arr[i]=ar+i;(外部数组的时候就不一样了会有坑)

代码
   
     

#include
< iostream >
using namespace std;
const int Max = 5 ;

int fill_array( double ar[], int limit);
void show_array( const double ar[], int n);
void revalue( double r, double ar[], int n);

int main()
{
double properties[Max];
int size = fill_array(properties,Max);
show_array(properties,size);
cout
<< " Enter revaluation factor: " ;
double factor;
cin
>> factor;
revalue(factor,properties,size);
show_array(properties,size);
cout
<< " Done!\n " ;

return 0 ;
}

int fill_array( double ar[], int limit)
{
double temp;
int i;
for (i = 0 ; i < limit; i ++ )
{
cout
<< " Enter value # " << i + 1 << " : " ;
cin
>> temp;
if ( ! cin)
{
cin.clear();
while (cin. get () != ' \n ' )
continue ;
cout
<< " Bad input;input process terminated.\n " ;
break ;
}
else if (temp < 0 )
break ;
ar[i]
= temp;
}
return i;
}


void show_array( const double ar[], int n)
{
for ( int i = 0 ; i < n; i ++ )
{
cout
<< " Property # " << i + 1 << " :$ " ;
cout
<< ar[i] << " \n " ;
}
}

void revalue( double r, double ar[], int n)
{
for ( int i = 0 ; i < n; i ++ )
ar[i]
*= r;
}

6、创建显示数组很简单,但要确保显示函数不能修改原数组,除非函数的目的就是修改传输的给的数据,否则应使用const保护,如void show_array(const double ar[],int n);   ar[]将被视为只读;

代码
   
     

#include
< iostream >
using namespace std;
int c_in_str( const char * str, char ch);
int main()
{
char * wail = " ululate " ;
char mmm[ 15 ] = " minimum " ;
int us = c_in_str(wail, ' p ' );
int ms = c_in_str(mmm, ' m ' );

cout
<< us << " times in wail.\n " ;
cout
<< ms << " times in mmm.\n " ;
cout
<< " Done!\n " ;

return 0 ;
}

int c_in_str( const char * str, char ch)
{
int counts = 0 ;
while ( * str)
{
if ( * str == ch)
counts
++ ;
str
++ ;
}
return counts;

}


/*
0 times in wail.
3 times in mmm.
Done!
Press any key to continue
*/

 

7、返回字符串的函数:

代码
   
     
#include < iostream >
using namespace std;
char * bulidstr( char c, int n);
int main()
{
int times;
char ch;
cout
<< " Enter a character: " ;
cin
>> ch;
cout
<< " Enter an integer: " ;
cin
>> times;
char * ps = bulidstr(ch,times);
cout
<< ps << " \n " ;
delete []ps;
ps
= bulidstr( ' + ' , 20 );
cout
<< ps << " -DONE- " << ps << " \n " ;
delete []ps;

return 0 ;
}


char * bulidstr( char c, int n)
{
char * pstr = new char [n + 1 ];
pstr[n]
= ' \0 ' ;
while (n --> 0 )
pstr[n]
= c;
return pstr;
}

/*
Enter a character:V
Enter an integer:46
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
++++++++++++++++++++-DONE-++++++++++++++++++++
Press any key to continue
*/

 

8、C++禁止将const 的地址赋给非const指针,而将非const指针赋值给const指针是可以的
如:const float g_earth=9.80:            |            const float g_moon=1.63;                      
       const float *pe=&g_earth;             |             float *pm=&g_moon;
       这两条是可行的                             |            这两条不可行

注意:如果数据类型本身并不是指针,则可以将const数据或者非const数据的地址赋给指向const的指针,但只能将非const数据的地址给非const指针;

9、函数和结构;189

代码
   
     
// 函数和结构——传递和返回结构
#include < iostream >
using namespace std;

struct travel_time
{
int hour;
int mins;
};

const int min_per_hr = 60 ;

travel_time sum(travel_time t1,travel_time t2);
void show_time(travel_time t);

int main()
{
travel_time day1
= { 5 , 45 };
travel_time day2
= { 4 , 55 };

travel_time trip
= sum(day1,day2);
cout
<< " Two days total: " ;
show_time(trip);

travel_time day3
= { 4 , 32 };
cout
<< " Three days total: " ;
show_time(sum(trip,day3));
cout
<< " Done!\n " ;

return 0 ;
}

travel_time sum(travel_time t1,travel_time t2)
{
travel_time yes;
yes.mins
= (t1.mins + t2.mins) % min_per_hr;
yes.hour
= (t1.hour + t2.hour) + (t1.mins + t2.mins) / min_per_hr;
return yes;
}

void show_time(travel_time t)
{
cout
<< " total time is: " << t.hour << " hours "
<< t.mins << " mins.\n " ;
}

/*
Two days total:total time is:10 hours 40 mins.
Three days total:total time is:15 hours 12 mins.
Done!
Press any key to continue
*/

10、*pf(int)意味着pf()是一个返回指针的函数,而(*pf)(int)意味着pf是一个指向函数的指针;

 

11、递归打印图形

你可能感兴趣的:(C++ Primer Plus)