各類編程語(yǔ)言介紹_第1頁(yè)
各類編程語(yǔ)言介紹_第2頁(yè)
各類編程語(yǔ)言介紹_第3頁(yè)
各類編程語(yǔ)言介紹_第4頁(yè)
各類編程語(yǔ)言介紹_第5頁(yè)
已閱讀5頁(yè),還剩55頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

-1MoreProgrammingConcept

各類編程語(yǔ)言介紹

-2目錄VariableandmemoryArrayvs.pointerMoreaboutforLoopC++stringI/OandFilehandlingOthertopics

-3Auto變量不可占太多memoryAuto變量就是沒(méi)寫static

的Local變量Auto變量是在進(jìn)入函數(shù)時(shí)才在STACK區(qū)安排存儲(chǔ)器,

在離開(kāi)函數(shù)(return)時(shí)就還掉(改變StackPointer)STACK區(qū)一般不會(huì)很大(幾拾KBytes)Auto變量用STACK區(qū),所以太大的array不能用叫用函數(shù)時(shí),returnaddress也會(huì)被推入

STACK

參數(shù)傳遞也是用STACK區(qū)

C/C++推入?yún)?shù)時(shí)是先推入最后一個(gè)參數(shù),這使得第一個(gè)參數(shù)會(huì)在堆棧的最上方,進(jìn)入函數(shù)時(shí),STACK中

returnaddress之下就是第一個(gè)參數(shù)

C/C++離開(kāi)函數(shù)時(shí),函數(shù)不負(fù)責(zé)拿掉STACK中

的參數(shù),那是叫用函數(shù)那個(gè)程序的責(zé)任!(與其它語(yǔ)言不同)

-4Auto變量占用STACK區(qū)memoryAuto變量就是沒(méi)寫static

的Local變量CPUIPSPInstructionPointerStackPointer系統(tǒng)區(qū)系統(tǒng)區(qū)程序+靜態(tài)dataHEAP堆積STACK

-5Static變量?Global變量都是static

的變量Local變量就是在函數(shù)內(nèi)的變量有補(bǔ)static修飾詞則為static變量沒(méi)有補(bǔ)static修飾詞則為Auto變量static

的變量在程序開(kāi)始RUN之前就存在,且已經(jīng)設(shè)好初值,程序結(jié)束后才會(huì)還掉所占存儲(chǔ)器寫了extern表示只是宣告,不是定義(define)Local變量就只能在該函數(shù)內(nèi)存取Global變量則只要看得見(jiàn)它的任一函數(shù)都能存取它宣告之后就看得見(jiàn),沒(méi)宣告就定義則看作同時(shí)宣告了注意main()也是函數(shù),沒(méi)有特別偉大!

-6Global,StaticLocal,Auto變量#include<stdio.h>

externintx;/*只有宣告,還不知道位置在何處?*/intfa();intfb(){intans=0;return++ans;}intmain(){intkk=123;cout<<"fa()="<<fa()<<fa()<<fa()<<kk<<endl;cout<<"fb()="<<fb()<<fb()<<fb()<<endl;return0;/*0inmain()meansOK*/}intx,y;/*真的x在這,也可以寫在另一個(gè)file中*/intfa(){/*…*}寫了extern表示只是宣告,不是定義(define)

-7StaticGlobal變量#include<stdio.h>#defineBUFSIZE100

staticcharbuf[BUFSIZE];

staticintbufp=0;intgetch(){/*...*/}voidungetch(intc){/*...*/}參考K&R課本4.6節(jié)也參考stack的push和pop寫在同一獨(dú)立file中,push和pop共享data

-8再談StaticGlobal變量#include<stdio.h>#defineRAND_MAX65535

staticunsignedlongseed=0;/*global*/intrand(){

seed=seed*1103515245+12345;returnseed%(RAND_MAX+1);}voidsrand(intnewseed){

seed=newseed;}參考K&R課本4.6節(jié)Pseudorandomnumber

-9register變量,volatile變量#include<stdio.h>enum{BUFSIZE=100,NSTU=60};

registerintwrong;/*thisiswrong,global不可*/volatileinthaha;voidmyfun(registerintx){

registerintyy,i;/*OK*/int*p;/*...*/p=&yy;/*thisiswrong*/}參考K&R課本4.7節(jié)

-10volatile變量#include<stdio.h>volatileinthaha;/*tellcompiler…*/intmain(){intk;doubleans;for(k=1;k<=99;++k){/*...*/ans=haha*haha;/*donotoptimize*/printf("ans=%f\n",ans);}}參考K&R課本4.7節(jié)

-11再談Array與pointershortintx[]={0,1,2,3,4,5,6,7};long*p=x;/*意思是p=&x[0];*/longans;intmain(){ans=*p;/*同:ans=p[0];*/printf("ans=%ld,p2=%ld\n",ans,p[2]);}注意byteorder,bigendianvs.littleendianp[2]與*(p+2)

完全相同pointer本身是一個(gè)整數(shù)指向別的存儲(chǔ)器

-12再論forLoop for之中規(guī)中矩用法就是明顯在數(shù)(count)loop次數(shù)(若不知要Loop幾次則建議用while)for與array配合使用PascalTriangleMagicSquare順便做些事的for

-13for之中規(guī)中矩用法強(qiáng)掉loop次數(shù):以下四例都是做9次for(i=1;i<=9;++i)/*…*/;for(i=1;i<=9;i++)/*…*/;for(i=1;i<10;++i)/*…*/;for(i=1;i<10;i++)/*…*/;參考之前9x9乘法表,Pascal三角形

-14for與array配合使用仔細(xì)看Pascaltriangle

例子UsingTwodimensionalarrayUsingonedimensionalarray仔細(xì)看MagicSquare

例子注意奇數(shù)階魔方陣之做法轉(zhuǎn)個(gè)想法就變成可直接用雙層forloop注意4的倍數(shù)階魔方陣之重點(diǎn)在如何判斷某格子是否在所謂的對(duì)角線上

-15再看4k階的魔方陣4的倍數(shù)階MagicSquare之重點(diǎn)在如何判斷該格子x[row][col]是否在對(duì)角線上注意畫對(duì)角線時(shí)是每個(gè)4x4方陣為單位但填入數(shù)值時(shí)是以整個(gè)方陣由左而右由上而下填入1到最后一個(gè)數(shù)(nextslides)Index由0算起與由1算起要如何調(diào)整?(C/C++/Java語(yǔ)言index是由0算起)

-16順便做些事的forloop(1/4)K&R1.5.1檔案復(fù)制

intc;c=getchar();while(c!=EOF){putchar(c);c=getchar();}#defineEOF(-1)intc;c=getchar();for(;c!=EOF;){putchar(c);c=getchar();}

-17順便做些事的forloop(2/4)intc;

for(c=getchar();c!=EOF;c=getchar()){putchar(c);

}

-18順便做些事的forloop(3/4)1.5.2Countingcharacterslongnc;nc=0;while(getchar()!=EOF)++nc;/*…*longnc;nc=0;for(nc=0;getchar()!=EOF;++nc);/*…*

-19順便做些事的forloop(4/4)K&R1.9統(tǒng)計(jì)file中出現(xiàn)各字K&R2.6K&R2.7atoiK&R2.8squeezeK&R3.5atoiK&R3.7trimK&R4.2atof

-20<algorithm><bitset>

<complex><deque><exception><fstream>

<functional><iomanip><ios><iosfwd><iostream><istream><iterator><list>

<locate><limits><map><memory>

<new><numeric><ostream><queue>

<streambuf>

<string><set><sstream>

<stack>

<stdexcept><typeinfo><utility>

<valarray>

<vector><cmath> C++classLibrary

-21TheC++StringClassTheC-stylestrings(arraysofchar)thatyou’vebeenusingarenottheonlywayofmanagingcharacterdata.C++allowsyoutoworkwithastringclassthateasesmanyoftheproblemsyou’veencounteredwithC-stylestrings.Inparticular,youdon’thavetoworryaboutmanagingmemoryforthestringdata.

-22C++StringBasicsThebasiccharactertemplateclassisbasic_string<>.Ithastwospecializations(generatedusingtypedefs),stringandwstring.stringcorrespondstotheC-stylestring(I.e.,const*char).wstringisanextensionforlanguagesthatusecharacters.Youcancopy,assign,andcomparestringsjustlikeyouwouldcopy,assign,andcompareprimitivetypes(int,double)stringa=“Hello”;stringb=string(a);stringc=a;boold=(a==b);

-23usingtheStringtypesIntheheaderfile<string>(Note,no.h)Allsuchfunctionsandothernamesareinthenamespacestd.Thebasicclassnameisatemplateclass,basic_string<>.Stringconstructorsstring()//emptystring(strings)//copyofsstring(strings,intstart)//substringstring(strings,intstart,intlen)//substringstring(char*a)//C-stringstring(intcnt,charc)//oneormorecharsstring(char*beg,char*end)//[beg,end)

-24AccessingIndividualCharactersIt’salmostlikeforaC-string.strings=“Harry”;s[0]is‘H’s[1]is‘a(chǎn)’

…s[5]isundefined!!!!–no‘\0’attheend

-25C++stringOperations=isusedtoassignavalue(char,C-string,orstring)toastring.+=isusedtoappendastring,character,orC-stringtoastring.+isusedtoconcatenatetwostringsorastringwithsomethingelseBooleanoperationsdoadictionaryordercomparison<<and>>areusedforinputandoutput.Oninput,leadingwhitespaceisskipped,andtheinputterminateswithwhitespaceorendoffile.

-26OtherC++stringOperationsswap(a,b);//swapthegutsofawithbs.append(s2);//appends2toss.c_str();//returnaC-strings.push_back(c);//appendachars.erase(various);//erasessubstringss.insert(various);//insertssubstringss.clear();//removesallcontentss.resize(cnt);//changethesizeofstocnts.replace(various);//replacescharacterss.size();//howmanycharacters?s.length();//howmanycharacters?s.max_size();//maximumnumberofchar?s.empty();//issempty?s.capacity();//sizewithoutreallocations.reserve(cnt);//reservesmemory

-27Usingc++stringstrings="Harry";s.data()//returnssasadataarray,no'\0'.s.c_str()//returnssasaC-string

with'\0'inti=atoi(s.c_str());//conversionchar*carray=newchar[80];s.copy(carray,79);//copiesupto79char

-28I/OandFileHandlingUsingSystemcallopen,read,write,closeUsingfilepointerFILE*stdin,*stdout,*stderr,*fp;UsingC++fileobject

-29C/C++I/OfunctionsCLibrary有關(guān)I/O的宣告在<stdio.h>(C++有關(guān)I/O的宣告在<iostream>)printf(char*,…)是一個(gè)函數(shù)(function),不是特殊statement!scanf(char*,…)也是function,注意要傳變量的address給它!格式很復(fù)雜,必須小心使用!

-30再談I/O(1/6)Readanintegerfromkeyboardscanf("%d",&x);/*notgood*/--betterapproachstaticcharbuf[99]gets(buf);/*netsafe*/x=atol(buf);/*x=atof(buf);*/--goodapproach:usefgets()insteadofgets()fgets(buf,sizeof(buf),stdin);實(shí)數(shù)用atof()注意

fgets讀入時(shí)尾巴比用

gets多了newline參考

K&R課本附錄B

-31再談I/O(2/6)讀入多個(gè)資料

intm,n;doublex,y;charbuf[99];fgets(buf,sizeof(buf),stdin);n=sscanf(buf,"%d%f%f",&m,&x,&y);Otherusefullibraryfunctionsstrtol,strtod(類似atol,atof)strtok,strsep(切token用)Thestrsep()functionisintendedasareplacementforthestrtok().

-32再談I/O(3/6)Use“f”functiontoopen/read/writefile

FILE*fp;

fp=stdin;/*從鍵盤standardinput*/fp=fopen("abc.txt","rt");/*"rb"forreadingbinaryfile*/if(fp==0){/*errorwhentrytoopen*/}fscanf(fp,"format_string",…);/*fread()forbinaryfile*/fp=fopen("abc.txt","wt");/*"wb"forwritingbinaryfile*/fprintf(fp,…);/*fwrite()forbinaryfile*/sprintf(buf,…);/*writeintothechararraybuf*/fseek(FILE*fp,intoffset,intfence);fclose(FILE*fp);if(feof(fp)){/*endoffile*/}if(ferror(fp)){/*...*/clearerr(fp);}/*fileerror,cleartheerrorflag!*/See

"manfopen"參考

K&R課本附錄B

-33再談I/O(4/6)

FILE*fopen(constchar*path,constchar*mode);''rt''Opentextfileforreading.Thestreamispositionedatthebeginningofthefile./*''rb''forbinaryfile*/''r+''Openforreadingandwriting.Thestreamispositionedatthebeginningofthefile.用fread讀binaryfile.用fwrite讀binary.fread/fwrite讀寫都不轉(zhuǎn)換.''w''Truncatefiletozerolengthorcreatetextfileforwriting.Thestreamispositionedatthebeginningofthefile.''wb''forwritingbinaryfile.讀寫不轉(zhuǎn)換意思是存儲(chǔ)器內(nèi)外資料相同

''w+''Openforreadingandwriting.Thefileiscreatedifitdoesnotexist,otherwiseitistruncated.Thestreamispositionedatthebeginningofthefile.''a''Openforwriting.Thefileiscreatedifitdoesnotexist.''a+''Openforreadingandwriting.Thefileiscreatedifitdoesnoexist.See

"man3fopen"

-34再談I/O(5/6)Usesystemcalltoopen/read/writefile

inthd;hd=open("abc.txt",O_RDONLY);/*0*/if(hd==-1){/*errorwhentrytoopen*/}n=read(hd,buf,nbytes);n=write(hd,buf,nbytes);lseek(inthd,intoffset,intfence);close(hd);SeenextslideSee

"man2open"參考

K&R課本附錄B

-35#include<fcntl.h>

inthd=open("file.ext",flag);

O_RDONLYopenforreadingonlyO_WRONLYopenforwritingonlyO_RDWRopenforreadingandwritingO_NONBLOCKdonotblockonopenO_APPENDappendoneachwriteO_CREATcreatefileifitdoesnotexistO_TRUNCtruncatesizeto0O_EXCLerrorifcreateandfileexistsO_SHLOCKatomicallyobtainasharedlockO_EXLOCKatomicallyobtainanexclusivelockO_DIRECTeliminateorreducecacheeffectsO_FSYNCsynchronouswritesO_NOFOLLOWdonotfollowsymboliclinksflagforopenSystemcall再談I/O(6/6)See

"man2open"

-36C++I/OfacilityC++uses

typesafeI/OEachI/Ooperationisautomaticallyperformedinamannersensitivetothedatatype(operatoroverloading,actually)InC,whataboutthis:printf("%d",float_data);StandardI/OstreamsasObjects:InC:stdin,stdout,stderr(#include<stdio.h>)InC++:cin,cout,cerr(#include<iostream>)

-37C++classesforI/O

-38IostreamLibraryHeaderFiles<iostream.h>:Contains

cin,cout,cerr,andclogobjects

(新版用<iostream>)<iomanip.h>:Containsparameterizedstreammanipulators(新版用<iomanip>)

<fstream.h>:

Containsinformationimportanttouser-controlledfileprocessingoperations(新版用<fstream>)

-39C++I/Oclassesandobjectsios:istreamandostreaminheritfromiosiostreaminheritsfromistreamandostream.istream:inputstreams cin>>someVariable;cinknowswhattypeofdataistobeassignedtosomeVariable(basedonthetypeofsomeVariable).ostream:outputstreamscout

<<someVariable;cerr

<<“Somethingwrong:“<<haha<<endl;

-40StreamInput/OutputClassesandObjects(1/2)ios:istreamandostreaminheritfromiosiostreaminheritsfromistreamandostream.<<(left-shiftoperator)Overloadedasstreaminsertionoperator>>(right-shiftoperator)

OverloadedasstreamextractionoperatorBothoperatorsusedwithcin,cout,cerr,clog,andwithuser-definedstreamobjects

-41StreamInput/OutputClassesandObjects(2/2)istream:inputstreams cin>>someVariable;cinknowswhattypeofdataistobeassignedtosomeVariable(basedonthetypeofsomeVariable).ostream:outputstreamscout

<<someVariable;coutknowsthetypeofdatatooutputcerr

<<someString;Unbuffered-printssomeStringimmediately.clog

<<someString;Buffered-printssomeStringassoonasoutputbufferisfullorflushed

-42StreamOutputostream:performsformattedandunformattedoutputUsesputforcharactersandwriteforunformattedcharactersOutputofnumbersindecimal,octalandhexadecimalVaryingprecisionforfloatingpointsFormattedtextoutputs

-43Stream-InsertionOperator<<isoverloadedtooutputbuilt-intypesCanalsobeusedtooutputuser-definedtypescout<<‘\n’;

Printsnewlinecharactercout<<endl;endlisastreammanipulatorthatissuesanewlinecharacterandflushestheoutputbuffercout<<flush;flushflushestheoutputbuffer

-44StreamInput>>(stream-extraction)UsedtoperformstreaminputNormallyignoreswhitespaces(spaces,tabs,newlines)Returnszero(false)whenEOFisencountered,otherwisereturnsreferencetotheobjectfromwhichitwasinvoked(i.e.cin)Thisenablescascadedinputcin>>x>>y;>>controlsthestatebitsofthestreamfailbitsetifwrongtypeofdatainputbadbitsetiftheoperationfails

-45C++I/OclassMemberFunctionscin.get():inputsacharacterfromstreamcin.get(c):inputsacharacterfromstreamandstoresitinccin.get(array,size);cin.getline(array,size);cin.ignore(3388,“\n”);cin.putback();intc=cin.peek();cout<<setprecision(2)<<x;cout.precision(2);cout<<hex<<123<<endl;

-46Sampleusingiostream#include<iostream>usingnamespacestd;intmain(){ cout.precision(4); cout.width(8); cout<<12.358<<endl; cout.fill('*'); cout.width(8); cout<<12.135<<endl; cout<<"HaHa"<<endl; cout.width(12); cout.setf(ios::left); cout<<135.625<<endl; return0;}

-47Sampleusing<iomanip>#include<iostream>#include<iomanip>usingnamespacestd;intmain(

){ intn; cout<<"Enteradecimalnumber:"; cin>>n; cout<<n<<"inhexadecimalis:" <<hex<<n<<'\n‘;

cout <<dec<<n<<"inoctalis:" <<oct<<n<<'\n' <<setbase(10)<<n;cout<<"indecimalis:"

<<n<<endl; return0;}

-48UsingfstreaminC++#include<iostream.h>#include<fstream.h>intmain(){ ofstreamout("myscore.txt"); if(!out) {

cout<<"Cannotopenfilemyscore.txt.\n";

return1; } out<<"C++"<<89.5<<endl; out<<"English"<<93.5<<endl; out<<"Maths"<<87<<endl; out.close(); return0;}

-49Openbinaryfilestaticchara[512];直接在宣告/定義時(shí)給參數(shù):ofstreamwf(″data.dat″,ios∷binary);wf.write((char*)a,len);宣告/定義后再openofstreamwf;wf.open(″data.dat″,ios∷binary);wf.write((char*)a,sizeofa);

-50打開(kāi)方式說(shuō)明ios∷in打開(kāi)檔進(jìn)行讀操作,這種方式可避免刪除現(xiàn)存檔的內(nèi)容ios∷out打開(kāi)檔進(jìn)行寫操作,這是默認(rèn)模式ios∷ate打開(kāi)一個(gè)已有輸入或輸出檔并查找到檔尾ios∷app打開(kāi)檔以便在檔的尾部添加資料ios∷nocreate如果檔不存在,則打開(kāi)操作失敗ios∷noreplace如果設(shè)置了ios∷ate或ios∷app,則可打開(kāi)已有檔,否則不能打開(kāi)ios∷binary指定檔以二進(jìn)制方式打開(kāi),默認(rèn)為文本方式ios∷trunc如檔存在,將其長(zhǎng)度截?cái)酁榱悴⑶宄袃?nèi)容C++檔案打開(kāi)方式的選項(xiàng)

-51MovingFilepointer(1/2)istream&istream∷seekg(〈position〉);istream&istream∷seekg(〈offset〉,〈參照位置〉);longitream∷tellg();其中,〈position〉和〈offset〉都是long型,用byte(字節(jié))數(shù)表示?!磪⒄瘴恢谩涤腥缦聨追N:

cur=1相對(duì)于當(dāng)前filepointer位置

beg=0相對(duì)于串流的開(kāi)始位置 end=2相對(duì)于串流的結(jié)尾位置myfile.seekg(-38,1);

-52MovingFilepointer(2/2)ostream&ostream::seekp(〈position〉);ostream&ostream::seekp(〈offset〉,〈參照位置〉);longostreamtellp();〈參照位置〉有如下幾種:

cur=1相對(duì)于當(dāng)前filepointer的位置

beg=0相對(duì)于串流的開(kāi)始位置 end=2相對(duì)于串流的結(jié)尾位置

-53Sampleusingofstream(1/2)#include<iostream>#include<fstream>structTVChannel{ intchannelNum;

charchannelName[38];};voidoutputLine(ostream&output,constTVChannel&c);intmain(

){ ofstreamoutTV("tvinfo.dat",ios::ate

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論