??xml version="1.0" encoding="utf-8" standalone="yes"?>
1) Ignoring the Keyboard
Your programm does not need to act on every keyboard message it received,Window handle many keyboard message function itself.
2)Who's Got thefocus
Though the keyboard is shared by all the window in the application ,The DispatchMessage send the message to the window procedure associated the window which message is intended.
The window that receives a particular keyboard event is the window has the input foucs.
Sometime no window has input foucs,this is the case if all your programs have been minmized,window continue send keyboard to the active window ,but it is send in the deffert form from sending to the input foucs.
A window procedure can be determine when its window has the input focus by trapping WM_SETFOCUS and WM_KILLFOCUS.
3) Queues and Synchronization
As the user presses and releases key on keyborad,Windows and keyboard device driver translate the hardware scan code into formatted message.Howerver the messages are not palced on the application queue right away,Instean Windows store these message in a system message queue .The System message queue is a single message maintained by windows specifically for the prelimary storage of user input from keyboard and the mouse. Window will take the next message from the system message queue and place it on the application message queue only when a window application has finished proecssing the previous user input message.
4) Keystorkes and Character
The message that an application receives from windows about keyboard events distingush between keystrokes and characters.
for instance The keysokes has only one key labbed 'A' ,and the character may be 'a' or 'ctr-a' etc.
2 Keystroke Message
1)Wirtual key Codes
The virtual key code is stored in the wParam parameter of WM_KEYDOWN,WM_KEYUP,the code identifies the key being pressed or release.
2)lParam Information
the wParam message parameter contain virtual key code and the lparam message parameter contains other information in understanding the keystoke.
3) Shift States
iState = GetKeyState (VK_SHIFT) ;
iState variable will be negative if the Shift key is donw
iState = GetKeyState (VK_CAPITAL) ;
4)Using Keystroke Messages
5)
case WM_KEYDOWN:
switch (wParam)
{
case VK_HOME:
SendMessage (hwnd, WM_VSCROLL, SB_TOP, 0) ;
break ;
case VK_END:
SendMessage (hwnd, WM_VSCROLL, SB_BOTTOM, 0) ;
break ;
case VK_PRIOR:
SendMessage (hwnd, WM_VSCROLL, SB_PAGEUP, 0) ;
break ;
3 Character Messages
Message Key or Code
WM_KEYDOWN Virtual key code for `A' (0x41)
WM_CHAR Character code for `a' (0x61)
WM_KEYUP Virtual key code for `A' (0x41)
Message Key or Code
WM_KEYDOWN Virtual key code VK_SHIFT (0x10)
WM_KEYDOWN Virtual key code for `A' (0x41)
WM_CHAR Character code for `A' (0x41)
WM_KEYUP Virtual key code for `A' (0x41)
WM_KEYUP Virtual key code VK_SHIFT (0x10)
Key Character Code Duplicated by ANSI C Escape
Backspace 0x08 Ctrl-H \b
Tab 0x09 Ctrl-I \t
Ctrl-Enter 0x0A Ctrl-J \n
Enter 0x0D Ctrl-M \r
Esc 0x1B Ctrl-[
case WM_CHAR:
[other program lines]
switch (wParam)
{
case `\b': // backspace
[other program line
break ;
case `\t': // tab
[other program lines]
break ;
case `\n': // linefeed
[other program lines]
break ;
case `\r': // carriage return
[other program lines]
break ;
default: // character codes
[other program lines]
break ;
}
return 0 ;
3)Displaying the window
When thee CreateWindow function return ,windows create a window internal.What it means is that windows allocate a block memory to store the imformation about the window.If you want to show that ,you should call
ShowWindow (hwnd, iCmdShow) ;
UpdateWindow (hwnd) ;
4) The Message Loop
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
typedef struct tagMSG
{
HWND hwnd ;
UINT message ;// message identifier
WPARAM wParam ;
LPARAM lParam ;
DWORD time ; // the time the message is placed on the message queen
POINT pt ; // the mouse coordiante
}
typedef struct tagPOINT
{
LONG x ;
LONG y ;
}
POINT, * PPOINT;
the message filed of message retrived from the message queen is anyting except WM_QUITm ,GetMessage return a nonzero value
wM_QUIT cause GetMessage reuturn 0.
TranslateMessage (&msg) ;
passing the msg struct back to window for some keysboard translation
DispatchMessage (&msg) ;
pass the msessageback to window .Windwo then send the message to the appropriate window procedure for processing.After window
procedure processing the message ,it return control to the windows,which is still in serving the Dispatchmessage
5) The Window Procedure
a The window procedure determined the how the window display on the client area and how the window respose to user input
b LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam),the four parameter is idential to the first four filed of the message struct.
6) Processing the Message
switch (iMsg)
{
case WM_CREATE :
[process WM_CREATE message]
return 0 ;
case WM_PAINT :
[process WM_PAINT message]
return 0 ;
case WM_DESTROY :
[process WM_DESTROY message]
return 0 ;
}
return DefWindowProc (hwnd, iMsg, wParam, lParam) ;
when a window procedure process the message ,it should return 0;
7) The WM_PAINT Message
WU_PAINT message is extremely import in window.it inform a program when part or all of the window 's client area are invalid and must be redraw or repaint.
WM_PAINT processing almost always begins with a call to BeginPaint:
hdc = BeginPaint (hwnd, &ps) ; //return a handle to device context
and ends with a call to EndPaint:
EndPaint (hwnd, &ps) ;
8)The WM_DESTROY Message
PostQuitMessage (0) ;
WNDCLASS, * PWNDCLASS ;
#include <windows.h>
/* the same as long _stdcall WndPro(long,unsign int,unsign int ,long)*/
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;
/*int _stdcall WinMain(long hInstance,long hPrevInstance,char * szComdLine,int iCmdShow)*/
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT ("HelloWin") ;
HWND hwnd ;
MSG msg ;
WNDCLASS wndclass ;
/*
all window createe based on this window class will completely repaint whenever horizational window sizd and vertial
window size change.
*/
wndclass.style = CS_HREDRAW | CS_VREDRAW ;
wndclass.lpfnWndProc = WndProc ; // set the window procedure for the window class
wndclass.cbClsExtra = 0 ;
wndclass.cbWndExtra = 0 ;
wndclass.hInstance = hInstance ; // the handle of this program
wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ;
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
wndclass.lpszMenuName = NULL ;
wndclass.lpszClassName = szAppName ;
if (!RegisterClass (&wndclass))
{
MessageBox (NULL, TEXT ("This program requires Windows NT!"),
szAppName, MB_ICONERROR) ;
return 0 ;
}
hwnd = CreateWindow (szAppName, // window class name
TEXT ("The Hello Program"), // window caption
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT, // initial x position
CW_USEDEFAULT, // initial y position
CW_USEDEFAULT, // initial x size
CW_USEDEFAULT, // initial y size
NULL, // parent window handle
NULL, // window menu handle
hInstance, // program instance handle
NULL) ; // creation parameters
ShowWindow (hwnd, iCmdShow) ;// iCmdShow determine how the window is to be initially displayed on the screen.
UpdateWindow (hwnd) ; // cause the client area to paint
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
return msg.wParam ;
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc ;
PAINTSTRUCT ps ;
RECT rect ;
switch (message)
{
case WM_CREATE:
PlaySound (TEXT ("hellowin.wav"), NULL, SND_FILENAME | SND_ASYNC) ;
return 0 ;
case WM_PAINT:
hdc = BeginPaint (hwnd, &ps) ;//return a handle to device context
GetClientRect (hwnd, &rect) ;// set the struct rect with the dimensions of the client area
DrawText (hdc, TEXT ("Hello, Windows 98!"), -1, &rect,
DT_SINGLELINE | DT_CENTER | DT_VCENTER) ;
EndPaint (hwnd, &ps) ;
return 0 ;
case WM_DESTROY:
PostQuitMessage (0) ;// insert a WM_QIUT in the message queue.
return 0 ;
}
return DefWindowProc (hwnd, message, wParam, lParam) ;
}
2 The Window Programming Hurdles
1)Queue and noqueue message
queue message are post the message queue and the noqueue message send to the window procdure directly.
2 双位字符?br />DBCSQdouble-byte character setQ最初的128个代码是ASCIIQ较高的128个代码中的某些L跟随著第
二个位元l。这两个位元l一PUC首位元组和跟随位元组Q定义一个字元?/p>
3 Unicode 解决Ҏ(gu)
Unicode是统一?6位元pȝQ也DBCS q样的同时含有一位和两位的字W集不同QUnicode 可以表示
65536 个字W?br /> Unicode 的缺Ҏ(gu)QUnicode 使用的空间是ASCII 的两?br />?宽字W和c
1 char
char c='A';
变量c 用一个字节来存储Q用16 q制表示?x41
char * p;
32 位系l,一ơ指针变量需要用4个字节表C?br /> char * p="Hello!";
字符串占?个字?其中 6个用于保存字W串Q?个用于保存中止符?
char [10]
占用10个字?br /> char a[]="Hello!";
占用 7个字?br /> 2 宽字?br /> typedef unsigned short whcar_t which is define in the window.h
与unsign short 一??6 字节Q两个字?br /> wchar_t c='A' 0x0041
wchar_t *p=L"Hello!" 指针占用 4个字??字符串占?14 个字?br /> 3 宽字元程序库函数
char * pc = "Hello!" ;
iLength = strlen (pc) ;
wchar_t * pw = L"Hello!" ;
iLength = wcslen (pw) ;
4 l护单一原始?br /> Microsoft Visual C++包含的TCHAR.H
如果定义了名为_UNICODE的识别字Qƈ且程式中包含了TCHAR.H表头档案Q那么_tcslen定义ؓ(f)wcslen
#define _tcslen wcslen
如果没有定义UNICODEQ则_tcslen定义为strlenQ?br /> #define _tcslen strlen
如果定义?_UNICODE识别字,那么TCHAR是wchar_tQ?br /> typedef wchar_t TCHAR ;
否则QTCHAR是charQ?br /> typedef char TCHAR ;
如果没有定义_UNICODE识别?br /> #define __T(x) x
#define _TQxQ?__TQxQ?br /> #define _TEXTQxQ?__TQxQ?/p>
?宽字节和windows
1 window 头文件中的类?br /> typedef char CHAR ;
typedef wchar_t WCHAR Q?br /> typedef CHAR * PCHAR, * LPCH, * PCH, * NPSTR, * LPSTR, * PSTR ;
typedef CONST CHAR * LPCCH, * PCCH, * LPCSTR, * PCSTR ;
typedef WCHAR * PWCHAR, * LPWCH, * PWCH, * NWPSTR, * LPWSTR, * PWSTR ;
typedef CONST WCHAR * LPCWCH, * PCWCH, * LPCWSTR, * PCWSTR ;
#ifdef UNICODE
typedef WCHAR TCHAR, * PTCHAR ;
typedef LPWSTR LPTCH, PTCH, PTSTR, LPTSTR ;
typedef LPCWSTR LPCTSTR ;
#else
typedef char TCHAR, * PTCHAR ;
typedef LPSTR LPTCH, PTCH, PTSTR, LPTSTR ;
typedef LPCSTR LPCTSTR ;
#endif
2 Windows 函数调用
#ifdef UNICODE
#define MessageBox MessageBoxW
#else
#define MessageBox MessageBoxA
#endif
3 Windows 的字W函?br /> ILength = lstrlen (pString) ;
pString = lstrcpy (pString1, pString2) ;
pString = lstrcpyn (pString1, pString2, iCount) ;
pString = lstrcat (pString1, pString2) ;
iComp = lstrcmp (pString1, pString2) ;
iComp = lstrcmpi (pString1, pString2) ;
4 在windows 使用printf
windows q不支持printf 但是可以使用sprintf
int printf (const char * szFormat, ...) ;
printf ("The sum of %i and %i is %i", 5, 3, 5+3) ;
int sprintf (char * szBuffer, const char * szFormat, ...) ;
char szBuffer [100] ;
sprintf (szBuffer, "The sum of %i and %i is %i", 5, 3, 5+3) ;
puts (szBuffer) ;
#include <windows.h>
int WINAPI WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
MessageBox (NULL, TEXT ("Hello, Windows 98!"), TEXT ("HelloMsg"), 0);
return 0 ;
}
1) #include <windows.h>包含其它的头文g
2) E序入口
int WINAPI WinMain Q HINSTANCE hInstance,HINSTANCE hPrevInstance,
PSTR szCmdLine,int iCmdShowQ?/p>
a #define WINAPI __stdcall 指定一个呼叫约定,包括如何生机器码,参数如何入栈
b HINSTANCE hInstance 执行体代P唯一标识该程?br /> c HINSTANCE hPrevInstance 已经不采?br /> d PSTR szCmdLine 参数列表
e int iCmdShow 昄方式
3) MessageBox 函数
MessageBox (NULL, TEXT ("Hello, Windows 98!"), TEXT ("HelloMsg"), 0);
参数1 H体代号
参数2 主题昄文字
参数3 标题昄文字
参数4 按钮Q? 为确?使用C语言的ORQ|Q操作符号将上面昄的一个常C代表内定按钮的常数组合:(x)
#define MB_OK 0x00000000L
#define MB_OKCANCEL 0x00000001L
#define MB_ABORTRETRYIGNORE 0x00000002L
#define MB_YESNOCANCEL 0x00000003L
#define MB_YESNO 0x00000004L
#define MB_RETRYCANCEL
#define MB_DEFBUTTON1 0x00000000L
#define MB_DEFBUTTON2 0x00000100L
#define MB_DEFBUTTON3 0x00000200L
#define MB_DEFBUTTON4
囄的外?br />#define MB_ICONHAND 0x00000010L
#define MB_ICONQUESTION 0x00000020L
#define MB_ICONEXCLAMATION 0x00000030L
#define MB_ICONASTERISK
#define MB_ICONWARNING MB_ICONEXCLAMATION
#define MB_ICONERROR MB_ICONHAND
#define MB_ICONINFORMATION MB_ICONASTERISK
#define MB_ICONSTOP
2 c 语言~译q程 c--compile -- .obj ---linking---- .exe
stdio.h 中声明?br />标准文gcd通过指针来进行存?FILE * fp;
2 c++ 式文gc?fstreamQifstream 和ofstreamQ分别对应读写,d写,q支持文本和二进制文
件?br /> 3 非缓冲文?br />?文g对话框组?br /> 1 OpenDialog 两种.TXT and .PAS 两种cd的过滤器?br /> 1) Filter OpenDaalog1->Filter="Text files{*.txt}|*.TXT|Pascal files{*.pas}|*.PAS";
同一个过滤器中,q可以有多种文g后缀
OpenDialog1->Filter="Pascal files|*.PAS;*.DPK;*.DPR";
2) FilterIndex 讄对话框一打开旉中的文件过滤。数g1开始计?br /> 3) InitialDir 讄对话框打开时定位的目录?br /> 4) Options
OpenPictureDialog1->Options.Clear();
OeenPictureDialog1->Options<<ofFileMustExist<<ofHideReadOnly<<ofNoChangeDir;
5) Title 讄对话框标题中昄的内宏V?br /> 2 SaveDialog l徏可以选择q保存文?br /> 3 OpenPictureDialog 可以选择q打开囑Ş文g?br /> 4 SavePictureDialog 可以选择q保存图形文件?br />?Win3? 相关lg
FileListBoxQDirectoryListBoxQDriveCombox,FilterComboBox
?常用文g理函数
1 文g函数常用函数
一个文件从记录盘上删除Q如果不存在或无法删除。则q回False?br /> extern PACKAGE bool __fastcall DeleteFile(const AnsiString FileName);
void __fastcall TFORM1::ButtonClick(TObject *Sender)
{
char buffer[256];
GetWindowsDirectory(buffer,sizeof(buffer));//获取Windows pȝ目录
AnsiString asFileName=FileSearch(Edit1->Text,GetCurrentDir()+AnsiString(";")
+AnsiString(buffer));//在当前目录下和windowspȝ}//目录下查询文件。?
if(asFileName.IsEmty()) ShowMessage(AnsiString("Couldn't Found")+Edit1->Text1);
2 FileSeek
extern PACKAGE int __fastcall FileSeek(int Handle, int Offset, int Origin);
extern PACKAGE __int64 __fastcall FileSeek(int Handle, const __int64 Offset, int Origin);
Description
Use FileSeek to reposition the read/write point in a file that was opened with FileOpen or
FileCreate. Handle is the file handle that was returned by FileOpen or FileCreate.
Offset specifies the number of bytes from Origin where the file pointer should be
positioned. Origin is a code with three possible values, denoting the beginning of the file,
the end of the file, and the current position of the file pointer.
Origin Action
0 The file pointer is positioned Offset bytes from the beginning of the file.
1 The file pointer is positioned Offset bytes from its current position.
2 The file pointer is positioned Offset bytes from the end of the file.
If FileSeek is successful, it returns the new position of the file pointer; otherwise, it
returns -1.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int iFileHandle;
int iFileLength;
int iBytesRead;
char *pszBuffer;
if (OpenDialog1->Execute())
{
try
{
iFileHandle = FileOpen(OpenDialog1->FileName, fmOpenRead);
iFileLength = FileSeek(iFileHandle,0,2);
FileSeek(iFileHandle,0,0);
pszBuffer = newchar[iFileLength+1];
iBytesRead = FileRead(iFileHandle, pszBuffer, iFileLength);
FileClose(iFileHandle);
for (int i=0;i<iBytesRead;i++)
{
StringGrid1->RowCount += 1;
StringGrid1->Cells[1][i+1] = pszBuffer[i];
StringGrid1->Cells[2][i+1] = IntToStr((int)pszBuffer[i]);
}
delete [] pszBuffer;
}
catch(...)
{
Application->MessageBox("Can't perform one of the following file operations: Open,
Seek, Read, Close.", "File Error", IDOK);
}
}
}
3FileExists
if(FileExist(SaveDialog1->FileName))
{
RenameFile(SaveDialog1->File,SaveDialog1->FileName+".bak");
}
iFileHandle=fileCreate(SaveSialog1->FileName);
for(int i=0;i<Memo2->Lines->String[i].length())
{
FileWrite(iFileHandle,Memo2->Lines->String[i].c_str(),length);
}
FileClose(iFileHandle);
4 FileGetAttrs
FileGetAttr returns the attributes of the file as a string of bits. This value is the same
as the Attr field of a TSearchRec struct. Check for individual attributes with code such as
the following:
int Attrs = FileGetAttr("MyFile.sys");
if x(Attrs & faHidden)
FileSetAttr("MyFile.sys", Attrs & !faHidden);
A return value of -1 indicates that an error occurred.
5 FileSetAttrs
FileSetAttr sets the file attributes of the file given by FileName to the value given by
Attr. The value of Attr is formed by combining the appropriate file attribute constants, as
in the following:
FileSetAttr("MyFile.sys", faReadOnly | faSysFile);
FileSetAttr returns zero if the function was successful. Otherwise the return value is an
error code.
?目录操作常用函数
1 CreateDir
#include <Filectrl.hpp>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if (!DirectoryExists("c:\\temp"))
{
if (!CreateDir("C:\\temp"))
throw Exception("Cannot create c:\\temp directory.");
}
}
2 ForceDirectories
ForceDirectories creates a new directory as specified in Dir, which must be a fully-
qualified path name. If the directories given in the path do not yet exist, ForceDirectories
attempts to create them.
ForceDirectories returns true if it successfully creates all necessary directories, false
if it could not create a needed directory.
Important
Do not call ForceDirectories with an empty string. Doing so causes ForceDirectories to
throw an exception.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
AnsiString Dir = "C:\Apps\Sales\Local";
if (ForceDirectories(Dir))
Label1->Caption = Dir + " was created";
}
3 GetCurrentDir
获取当前的目录完整的路径?br /> 4 RemoveDir
删除一个存在的目录Q目录必Mؓ(f)I?br /> 5 SetCurrentDir讄pȝ的当前目?
6 SelectDirectory
extern PACKAGE bool __fastcall SelectDirectory(constAnsiString Caption, const WideString
Root, AnsiString &Directory);
Call SelectDirectory to let the user enter a directory name.
Use the first syntax to display the Windows directory browser. The Caption parameter
specifies a caption for the dialog. The Root parameter specifies the root directory from
which to browse. The selected directory is returned as the Directory parameter. When using
this syntax,
SelectDirectory does not change the value of the current directory.
extern PACKAGE bool __fastcall SelectDirectory(AnsiString &Directory, TSelectDirOpts
Options, int HelpCtx);
enum TSelectDirOpt { sdAllowCreate, sdPerformCreate, sdPrompt };
typedef Set<TSelectDirOpt, sdAllowCreate, sdPrompt> TSelectDirOpts;
sdAllowCreate An edit box allows the user to type in the name of a directory that
does not exist. This option does not create a directory: the
application
must read the name of the selected directory and create it i
f desired.
sdPerformCreate Used only in combination with sdAllowCreate. If the user enters a
directory
name that does not exist, the directory selection dialog creates it.
sdPrompt Used only in combination with sdAllowCreate. Displays a message box
that informs the user when the entered directory does not exist
and asks if the directory should be created.
If the user chooses OK, the directory is created
if the option set includes sdPerformCreate.
If the option set does not include sdPerformCreate,
the directory is not created:
the application must read the directory name and create
#include <FileCtrl.hpp>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
AnsiString Dir = "C:\\Program Files\\MyApp";
if (SelectDirectory(Dir, TSelectDirOpts() << sdAllowCreate << sdPerformCreate <<
sdPrompt,1000))
Label1->Caption = Dir;
}
?驱动器常用函?br /> 1 DiskFree 指定驱动器中剩余I间的字节数
2 DiskSize 驱动器容?br />四文件名常用函数
1 ChangeFileExt
2 ExtractFileDir
3 ExtractFileDriver
4 ExtractFileExt
5 ExtractFileName
6 ExtractFilePath
7 ExtractRelativePath
实例
1
1
L a b e l 1 目录列表( & D ) : FocusControl: DirectoryListBox1
D i r e c t o r y L i s t B o x 1 D i r L a b e l : L a b e l 6 ;
FileList: FileListBox1
L a b e l 2 文g列表( & S ) : FocusControl: FileListBox1
F i l e L i s t B o x 1 FileEdit: Edit1
L a b e l 3 驱动? & R ) : FocusControl: DriveComboBox1
D r i v e C o m b o B o x 1 DirList: DirectoryListBox1
L a b e l 4 文gcd( & F ) : FocusControl: FilterComboBox1
F i l t e r C o m b o B o x 1 FileList: FileListBox1
Filter: 所有文?( * . * ) | * . * |文本文g( * . t x t ) | * . t x t
L a b e l 5 路径名:(x)
L a b e l 6 C : \ S a m p l e s \ S 0 6 B
L a b e l 7 文g? & N ) : FocusControl: Edit1
E d i t 1
B u t t o n 1 文g长度( & L ) . . . Te x t : * . *
#include<stdio.h>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
FILE* fp;
AnsiString FileFullName;
long size;
AnsiString PropertyMes;
FileFullName=Label2->Caption+"\\"+Edit1->Text;
if(FileExists(FileFullName))
{
fp=fopen(FileFullName.c_str(),"rt");
if(fp!=NULL)
{
fseek(fp,0L,SEEK_END);
size=ftell(fp);//get the length of file
PropertyMes="file is total"+IntToStr(size)+"bytes.";
MessageDlg(PropertyMes,mtInformation,TMsgDlgButtons() << mbOK, 0);
}else
{
MessageDlg(PropertyMes,mtWarning,TMsgDlgButtons() << mbOK, 0);
}
fclose(fp);
}
}
2 获取驱动器类型信?br /> UINT GetDriveType(
LPCTSTR lpRootPathName //获取根目录的路径名称
)
?-5 函数G e t D r i v e Ty p e的返回值及其含?br />?值 ???br />0 无法驱动器的类?br />1 根目录不存在
D R I V E _ R E M O VA B L E 可移动驱动器
D R I V E _ F I X E D 不可Ud驱动?br />D R I V E _ R E M O T E |络驱动?br />D R I V E _ C D R O M C D - R O M驱动?br />D R I V E _ R A M D I S K 虚拟驱动?/p>
Result=GetDriveType(Edit2->Text.c_str());
3 操作ini 文g
__declspec(dllimport) class __stdcall MyDllClass {
public:
MyDllClass();
void CreateAForm();
TDllFrm* DllMyForm;
};
静态调用,build 生成dll 文g和lib 文gQƈ把lib 文g导入到工E中
void __fastcall TForm1::Button1Click(TObject *Sender)
{ // 导出cd玎ͼ导出cd能用静态方式调?
DllClass = new MyDllClass();
DllClass->CreateAForm();
}
void __fastcall TForm1::Button2Click(TObject *Sender)
{ // 导出函数实现
CreateFromFunct();
}
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
delete DllClass;
}
动态调?br /> class TForm1 : public TForm
{
...
private: // User declarations
void (__stdcall *CreateFromFunct)();
...
}
HINSTANCE DLLInst = NULL;
void __fastcall TForm1::Button2Click(TObject *Sender)
{
if( NULL == DLLInst ) DLLInst = LoadLibrary("DLL.dll"); //上面?Dll
if (DLLInst) {
CreateFromFunct = (void (__stdcall*)()) GetProcAddress(DLLInst,
"CreateFromFunct");
if (CreateFromFunct) CreateFromFunct();
else ShowMessage("Could not obtain function pointer");
}
else ShowMessage("Could not load DLL.dll");
}
void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
if ( DLLInst ) FreeLibrary (DLLInst);
}
8 bcb 调用vc ~写的DLL
1Q?名字分解
1. 名字分解Q?
没有名字分解的函?
TestFunction1 // __cdecl calling convention
@TestFunction2 // __fastcall calling convention
TESTFUNCTION3 // __pascal calling convention
TestFunction4 // __stdcall calling convention
有名字分解的函数
@TestFunction1$QV // __cdecl calling convention
@TestFunction2$qv // __fastcall calling convention
TESTFUNCTION3$qqrv // __apscal calling convention
@TestFunction4$qqrv // __stdcall calling convention
使用 extern "C" 不会(x)分解函数?
2Q?br /> __cdecl ~省
?Borland C++ 的缺省的 C 格式命名U定Q它在标识符前加一下划U,以保?
它原来所有的全程标识W。参数按最双参数优先的原则传递给栈,然后清栈?
extaern "C" bool __cdecl TestFunction();
?def 文g中显CZؓ(f)
TestFunction @1
注释Q?@1 表示函数的顺序数Q将在“用别名”时使用?
__pascal Pascal格式
q时函数名全部变成大写,W一个参数先压栈Q然后清栈?
TESTFUNCTION @1 //def file
__stdcall 标准调用
最后一个参数先压栈Q然后清栈?
TestFunction @1 //def file
__fastcall 把参C递给寄存?
W一个参数先压栈Q然后清栈?
@TestFunction @1 //def file
3Q?br /> 3. 解决调用U定Q?
Microsoft ?Borland ?__stdcall 之间的区别是命名方式?Borland 采用
__stdcall 的方式去掉了名字起前的下划线?Microsoft 则是在前加上下划U,?
后加?@ Q再后跟为栈保留的字节数。字节数取决于参数在栈所占的I间。每一?
参数都舍入ؓ(f) 4 的倍数加v来。这U?Miocrosoft ?DLL 与系l的 DLL 不一栗?
4 查看dll 的调用接口tdump -ee MyDll.dll >1.txt (查看 1.txt 文g卛_)
5 ~辑c++ builder build Z个可以直接调用的 .exe ?点击project option 中linker 标签 Luser dynamic RTL 选项 和package ?Lbuilder with runtime package 选项.
6 调用代参数的vl ~写的dll 调用的实例?br />int (__cdecl *fun)(char*,char*,char*);
HINSTANCE DLLInst = NULL;
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if( NULL == DLLInst )
{
DLLInst = LoadLibrary("HollyIVRCard.dll");
}
if(DLLInst)
{
fun=(int (__cdecl*)(char*,char*,char*))GetProcAddress(DLLInst,"hTrade");
if(fun)
{
cardid=Edit1->Text.c_str();
num=Edit2->Text.c_str();
ShowMessage(fun(cardid,num,res));
//cout<<cardid<<endl;
//cout<<num<<endl;
}
} else{
ShowMessage("load dll fail");
}
ShowMessage(AnsiString(res));
}
2 using
void main()
{
using namespace car;
length;
using namespace phane;
model;
}
6 new 与delete q算W?br /> double * pd; // define pointer variable
pd=new double; // allocate memory
if(pd!=null)
{
...
delete pd; // free memory
}
double1=null
* pds=new double[100];
if(pds)
{
....
delete[] pds;
}
如果是用new q行内存I间分配没有成功Q则q回I指针null
释放一个数l分配的内存是,常常采用带[]的Ş?br />7 void 指针 它指向一个地址|但是不说名数据类型,可以使用void 指针创徏一个通用的函敎ͼ在?br /> 的时候将指针cd转化成相应的具体cd?br /> void ShowHex(void *pv,int siae)
{
....
((unsigned char *)pv)[i]
}
void main()
{
void *pv=null;
unsigned char c1=0x12;
pv=&c1;
ShowHex(pv,sizeof(c1));
}
9 typeid q算W?用来求得变量或队形爱奛_的数据类型,q回一个type_info cd的对象,通过该对?br /> 可以获取数据cd的名U?/p>
include<typeinfo.h>
int i;
const type_info &t0=typeid(i);
t0.name();
10 函数
1 模板函数
template<class T> T min(R &x,Tv&y)
{
return x<y?x:y;
}
2 指向函数的指?br /> int max(int x,int y)
{
...
}
int min(int x,int y)
{
...
}
int (* m_pfunction)(int,int);
void main()
{
m_pfunction=max;
(*m_pfunction)(2,3);
m_pfunction=min;
(*m_pfunction)(2,3);
}
11 cM对象
1 构在函数和析构函?br /> #include <iostream.h>
#include <string.h>
#include <conio.h>
class Book
{
private:
char * pBookName;
public:
int PageNum;
public:
Book(char * pBN=NULL);
~ B o o k ( v o i d ) ;
void SetBookName(char * pBN);
int GetBookName(char * pBN,unsigned int MaxSize);
} ;
Book:Book(char *PBN)
{
cout<<"构造函?<<endl;
pBookName=null;
if(oBN!=null)
{
pBookName=new char[strlen(pBN)+1];
if(pBookName!=null)
strcyp(pBookName,pBN);
}
}
Book::~Book()
{
delete[] pBookName;
}
void Book::SetBookName(char * pBN)
{
if(pBookNameQ=null)
delete[] pBookName;
pBookName=new char[strlen(pBN)+1];
if(pBookName!=null)
strcyp(pBookName,pBN);
}
int Book::GetBookName(char * pBN,unsigned intmaxSize)
{
if((pBookName!=null))&&(MaxSize>strlen(pBookName))
{
strcpy(pBN,pBookName);
retrun strlen(strlen(pBookName));
}
}
// 使用
Book b1;
b1.SetBookName("test");
Book b2(test1);
2 对象的引用参C?br /> void Add(Book b)
void AddRef(Book & b);
3 静态成员变?是一个公共变?br /> 在初始化 的时候利用作用运符:: 对私有类型的静态成员变量可以向公有cd的静态成变量一栯?br /> 但不能直接引?br /> 3 const cd成员函数与mutable
class CDate
{
public:
int year;
mutable int month;
CDate(int y=2000,int m=1)
{
year=y;
month=m;
};
int BetMonth() const ;//read only
void SetMonth(int m);// write only
}
void CDate::SetMonth(int m)
{
month=m;
}
void main()
{
CDate d1;
}
在const cd的成员函数定义中Q不可一直接或简介的修改普通类型的成员变量
如果象修改const cd对象的成员函敎ͼ可以使用关键字mutable 对该成员变量q行修改
5 对象的初始化与初始化?br /> 参数类表中的数D予成员变量时Q不仅可以在构造函数的函数体中q行Q以阿宽衣在初始化行中进?br /> 在初始化处惊醒初始化的情冉|Q?br /> 1 分层cȝ构在函数可以调用它的M一个子对象的构造函?br /> 2 对常量const cd的成员变量的初始化必d初始化行?br /> 3 对于引用cd的成员变量的初始化必d初始化行?br />
class CPoint
{
publicQ?br /> int x,y;
CPoint(int ax=0,int ay=0)
{
x=ax;
y=ay;
}
};
class CRect
{
private:
CPoint low_right;
CPoint up_left;
public:
int & CenterX;
const int CenterY;
CRect(int x1,int y1,int x2,int y2,int &x3,int y3)
:up_left(x1,y1),low_right(x2,y2),CenterX(x3),CenterY(y3)
{
}
};
void main()
{
int cx=5;
int cy=6;
CRect r1(1,2,3,4,cx,cy);
}
6 拯构造函?br /> 拯构造函C普通构造函数的差别在与参数类表,参数列表中有一个对象,该对象的数据cd?br /> 本类的一个引用,而且一般情况下Q该对象q应该是一个const cd的对象?br /> 如果在类的定义是不是昄的定义一个拷贝函敎ͼ则编译器?x)自动的定义一个拷贝构造函?br />
class CPoint
{
public:
int x,y;
CPoint(int m_x=0,ubt m_y=0); // default constructor
cPoint(const CPoint &c); //copy consrucotr
};
CPoint::CPoint(int m_x,int m_y)
{
}
CPoint::CPoint(const CPoint &c)
{
x=c.y;
y=c.x;
}
void main()
{
CPoint c1(1,2); //invoke default constructor
CPoint c2-c1; // invoke copy constructor
}
7 template class
template<class t,int Size>class Array // template class
{
private:
T arr[Size];
int CurSize;
public:
Array(T * date,int n)
{
CurSize=n<Size?n;Size;
for(int i=0;i<CurSize;i++)
{
Arr[i]=data[i];
}
}
}
void main()
{
int i1[10]={1,2,3,4,5,6,7,8,9};
Array<int,6>array_i1(i1,i0);
}
1 友员cd友员函数
#include <iostream.h>
#include<string.h>
#include<conio.h>
class SoftWareEngineer; //先对SoftwareEngineer c进行显C明一?/p>
class Computer // 定义Computer c?br />{
private:
int Price;
public:
Computer(int p){Price=p};
friend class SoftwareEngineer; //友员类载这里声?br /> frined void Judge(Computer &c,SoftwareEngineer & s) //友员函数
}Q?/p>
class SoftwareEngineer
{
int Salary;
char Name[20];
public:
SoftwareEngineer(int s,char *n //构造函?
{
Salary=s;
strcpy(Name,n);
}
int GetComputerPrice(Computer &c){return c.Price} //讉KComputer 的思友变量
friend void Judge(Computer &c,SoftwareEngineer & s) //友员函数
}Q?br />//判断一个Y件工E师是否可以用一个月的薪水买的器一台电(sh)?br />void Judge(Computer &c,SoftwareEngineer &s) //桥友员函?br />{
if(c.Price>s.Salary)
cout<<"软g工程?<<s.Name<<"的一个月薪水C起一台电(sh)?<<endl;
else
cout<<"软g工程?<<s.Name<<"的一月薪水买的v一台电(sh)?<<endl;
}
void main()
{
Computer c1(100);
SoftwareEngineer s1(120,"user1");
Judge(c1,s1);
SiftwareEngineer s2(80,"user2")
Judge(c1,s2);
getch();
}
2q算W重?
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class TValue{
private:
int value;
public:
TValue(int i){value=i}
//成员函数重蝲q算W?br /> TValue operator!();
TValue operator+(TValue & rv);
// 友员函数重蝲q算W?br /> friend ostream & operator<<{ostream & os,TValue & rv};
}
TValue Tvalue::operator!()
{
return TValue(!value);
}
TValue TValue:operator+(TValue& rv)
{
return TValue(value+rv.value);
}
ostream & operator<<(ostream & os,TValue rv)
{
os<<setw(5)<<rv.value;
return os;
}
void main()
{
TValue v1(3),v2(5);
cout<<
}
3 cȝz和?br />1class Box{
public:
int width,height;
void SetWidth(int w){width=w};
void SetWidth(int h){height=h;};
};
class TColorBox::public Box{
public:
int color;
void SetColor(int c){color=c;};
};
void main(){
TColorBox cb;
cb.SetColor(255); //声明非承类的对?br /> cb.SetWidth(100);//声明l承cȝ对象
cb.SetHeight(100); //声明l承cȝ对象
}
2 不能被承的成员
构造函敎ͼ析构函数Q用户定义的新操作符Q用户定义的赋值操作,友员关系
3 构造函敎ͼ析构函数的调用顺?br />class A{
int a,b,c;
public:
A(int x,int y,int z)
{
a=x;
b=y;
c=z;
}
};
class B{
int d;
public :
B(int xx):A(xx,xx+1,xx+2)(d=xx);//内联构造函?br /> B(int x,int y,int z,int xx);//非内联构造函?br /> B:B(int x,int y,int z,int xx):A(x,y,z)
{
d=xx;
}
}
实例
class Currency
{
poublic:
double par_value;
Currency(){per_value=0.0;}
Currency(double d){per_value=d;}
Currency(Currency &rc){par_value=rc.par_value;}
Currency & operator={Currency & c}
{
par_valuc=c.par_value;
return * this;
}
Currency & operator+(Currency & c)
{
par_value+=c.par_value;
return *this;
}
}
//人民?br /> class RMB:public Currency
{
public:
RMB():Currency(){};//调用zcȝ构造函数前Q需要调用器基类的工造函?br /> RMB(double d):Currency(d){};
RMB(Currency& c)QCurrency(c){};
RMB(RMB& rmb):Currency(rnb){};
friend ostream& operator<<{ostream& os,RMB& rnb};//zcȝ附加功能
}Q?br /> ostream& operator<<{ostream& os, RMB& rmb} //output q算W不能是一个类的成员函?br />{
os<<"K?<<setiosflags(ios::shwopoint|ios:fixed)<<setprecision(2)rmb.par_value;
return os;
}
void main()
{
RMB r_income(5000);
RMB r_balance;
r_balance=r_income=r_expense;
cout<<"income"<<r_income<<endl;
}
4 iostream q算W重?br /> 1)ostream & operator<< (ostream &os,const Triangular & ths)
{
os<<"("<<rhs.beg_pos()<<","<<rhs.length()<<")";
rhs.display(rhs.length(),rhs.beg_pos(),os);
}
ouutput q算W不能够设计成member function
2)istream& operator>>(istream &is,Triangular &rhs)
{
char ch1,ch2;
int bp,len;
//输入 ch1='(',bp=3,ch3=',' len=6
is>>ch1>>bp>>ch2>>len;
rhs.beg_pos(bp);
rhs.length(len);
rhs.next_reset();
return is;
}
Triangular tris;
cin>>tri2
4 虚基c?br />载承关pMQ同一基类被承多ơ,不仅?x)引器歧异,而v可能费I间
class A
{
public:
int value;
};
class B:public virtual A(); //虚基c?~译器只产生一个基cȝ本。如果不定义为virtual ~译器不知到调用那个value 了,当然
class C:public virtual A();// 也可以return B::value;
class D:public b.public c
{
public
int GetValue(){return value;}
};
void main()
{
D dd;
dd.GetValue();
}
5 多态ŞQ和虚函?br />class TFirst
{
public virtual void Display();
};
void TFirst::Display()
{
cout<<"first "
}
class TSecond:public TFirst
{
public:
virtual void Display();
};
void TSecond::Display()
{
cout<<"second"
}
void Display(TRist * pFirst)
{
pFisrt=>Display();
}
void main()
{
TFirst * pFirst=new TFirst;
TSecond * pSecond=new TSecond;
pFirst->Display();
pSecond->Display();
Display(pFirst);
Display(pSecond);
delet pfirst Q?br /> delet pSecond;
getch();
}
c++ builder 中的集合?br /> 1 集合的概念基?br /> Set<type,minval,maxval>
Set<char,'A','C'> s1
tydefef Set(char,1,255) UPPERCASet;
UPPERCASESet s1;
s1<<'A'<<'B'<<'C';
sysset.h 直接包含载vcl.h ?br /> 2 集合的操?br /> #include<iostream>
#include<system.hpp>
#include<conio.h>
using namespace std;
typedef Set<char,'B','Z'> UpperSet;
typedef Set<char,'a','z'> LoverSet;
typeder Set<char,'a','j'> HalfLowerSet;
void set_example()
{
LowerSet ae,ae2,ac,de;
UpperSet AE,AE2,AC,DE;
HalfLowerSet aj;
}
异常处理
1 c++ 的异常处?br /> #include <iostream.h>
#include <conio.h>
class Crange
{
public:
int index;
CRange(int i){index=i;}
}
class CString
{
char a[100];
int len;
public:
CString(char * s)
{
Len=strlen(s);
strcpy(a,s);
}
char & operator[](int i)
{
if(i>0 && i<len) return a[i];
else throw CRange(i);
}
void DisplayNoCatch(CString & s)
{
int j;
for(j=0lj<20;j++)
cout<<s[j]<<""endl;;
}
int DisplayHasCatch(CString & s)
{
try{
DisplayNoCatch(s);
}catch(CRange r)
{
cerr<<r.index<<endl;
}
return 99;
}
}
2 多\捕捉
#include<iostream.h>
#include<conio.h>
void MultiException()
{
int i;
double d;
int no;
cout<<"(>0 and <5)";
cin>>no;
tyr
{
switch(no)
{
case 1;
throw 123;
break;
case 2:
throw i;
break;
case 3:
throw d;
break;
case 4:
throw "Error";
break;
default:
cout<<"error";
}
}
catch(int ie)
{
cout<<"int"<<endl;
}
catch(double de)
{
cout<<"double"<<endl;
}
catch(char* se)
{
cout<<"char"<<endl;
}
}
3 bcb中的异常c?br /> 1)却省vcl 异常处理 无try catch 自动处理
int i=4,j=0;k;
k=i/k;
//下一句永q不?x)执?br /> ShowMessage(k);
2) 引发vcl 异常c?br /> try{
}
catch(Exception &e)
{
ShowMessage(e.,Message);
}
不能引发如int double {简单类型的异常
3) c++ 异常处理
try
{
throw 2222;
}
catch(int ErrorCode)
{
ShowMessage(ErrorCode);
}
}
4 单一捕捉异常
try{
k=10/0;
}catch(EDivByZero & E)
{
MessageDlg()
}
5 捕捉所有异?br /> try
{
}catch(...) or(EExternalException &E)
vector<int>::iterator it;
it=find(vec.begin(),vec.end,1024);
if(it!=vec.end())
//find...
list<int>::iterator it;
it=find(list.first().list.end,4);
4 所有容器的共同操作
equality(==),assignment(=),empty(),size(),clear()
begin() q回一个iterator,只向容器的第一个元?br /> end() q回一个iterator,只向容器的最后 一个元?br />5 使用序列容器
1 vector 和list 是两个最主要的序列式容器 vector 式一块连l的内存。取数据效率较高Q但是存数据
但是如果在Q意位|插入或删除数据Q效率就比较低。(但是在最后一位添加和删除数据效率都比较高Q?br /> 2 list pM双向q接来存储内存,可以L执行前进或后退操作Q可以在L位置安插或删除数据?br /> 3 deque 以连l的内存存储元素Q但是deque 在最前端元素的安插和删除操作更有?末端相同
4 #include<vector>
#include<list>
#include<deque>
5 产生I的容器
list<string> slist;
vector<int> ivec;
6 产生特定大小的容器,每个元素都以千默认的g为初?br /> list<int> ilist(1024);
vector<string> svec(32);
7产生特定大小的容器,qؓ(f)每个软速制定初?br /> vector<int> ivec(10,-1)
list<string> slist(16,'unassigned');
8 int ia[9]={1,2,3,4,5,6,7,8,9};
vector<int> fib(ia,ia+8);
9 Ҏ(gu)某个容器产生新容器,复制软来容器的元素,作ؓ(f)新容器的初?br /> list<string> slist;
list<string> slist2<slist>
10 push_back(),pob_back() 在容器末进行安插和删除操作。在deque和list可以用push_front
和pop_front 在最前面天加和删除操作?br /> 11 forntQ) 和back()可以取回最前和最后的值?br /> 12 iterator insert(iterator position,elemType value)value 安插于position 之前Q返回一个iterator
指向被安插的元素
list<int>ilist;
list<int>:: it=ilist.begin();
while(it!=ilist.end())
if(*it>=ival)
{
ilist.inert(it,ival);
break;
}
if(it==ilist.end())
ilist.pushi_back(ival);
}
8指针 指针为程序引入了一层间接性,我们可以操作指针Q代表某特定内存地址Q,而不再直接操控对象?br /> 指针主要形成两g事,可以增加E序本n的弹性,但同时也增加了直接操控对象时所没有的复杂度
1 int ival=1024
int *p=&ival; 其中*p 指int型对象的地址
2 指针所h的双重性,既可以让我们操控指针内含的内存地址Q也可以让我们操作指针所指定的对象?br /> pi 指定pi所含有的内存地址
*pi 核定ival的?br /> 3 指针的提领(dereferenceQ?br /> 如果pi d到某个对象,则执行提领操作,如果pi 不指定Q何对象,提领?x)导致未知的执行l果
一个ؓ(f)只想M对象的指针,其内含地址?Q我们称为nullQQ何指针都可以被初始话Q或是o(h)gؓ(f)0
if(pi&&...)
只有pi含一个非0值时Q其l果为true
vector<int> *pv=0;
const int seq_cnt=6;
vector<int> *seq_addres[seq_cnt]={
&fibonacci,&lucas,&pell...
};
一个指针数l,定w为seq_cntQ每个指针都指向vector<int>
4 #include<cstdlib>
rand(seed) q回一个介?和seed 之间的随机数
5 对象指针
if(!fibonacci.empty()&&....){
pv.empty()..
}
9 文g?br /> Ҏ(gu)件的dQ首先的含入fstream
#include<fstream>
1 ofstream outfile("seq_data.txt"); 如果文g不存在,产生一个文Ӟ如果文g已经存在Q这个文?br /> 被开启作出只用,但是源文件中的数据会(x)输调
2 ofstream outfile("seq_data.txt",ios_base::app) q加模式
3 oufile 为false 表示文g未开启成?br />10 文g?br /> ifstream 文件名传hQ如果文件未能开启成功,ifstream 对象被核定ؓ(f)false Q如果成功,为true
ifstream infile("seq_data.txt");
int num_tries=0;
int num_cor=0;
if(!infile){
//׃某种原因Q文件无法开?br /> }
else
{
string name;
int nt;
int nc;
while(infile>>name)
{
// 一旦读到到文g,infile false
// infile>>name>>nt>>nc ,把文?anna 24 19 分别dnameQntQnc ?br /> infile>>nt>>nc;
if(name==usr_name)
{
//find hime
count<<"Welcome back,"<<usr_name
<<"\nYour current score is" <<nc
<<" out of " <<nt<<"\nGood Luck"!\n";
num_tries=nt;
num_cor=nc;
}
}
11 同时d同一个文?br /> fstream iofile("seq_data.txt",ios_base::in|ios_base::app);
if(!iofile)
...
else
{
iofile.seekg(0); 文仉新定位的文g的最末端
}
12
#include<iostream>
#include<string>
using namespace std;
//---------------------------------------------------------------------------
#pragma argsused
int main()
{
string username;
cout<<"Please enter your name:";
cin>>username;
switch(username.size()){
case 0:
cout<<"with no name";
break;
case 1:
cout<<"with one character";
break;
default:
cout<<"hollo ,"<<username<<endl;
break;
}
return 0;
}
13
#include<iostream>
#include<vector>
#include<string>
using namespace std;
//---------------------------------------------------------------------------
int main()
{
vector<int> ivec;
string str;
int val;
while(cin>>val){
ivec.push_back(val);
}
int sum=0;
for(int i=0;i<ivec.size();i++){
sum+=ivec[i];
}
int average=sum/ivec.size();
cout<<"sum of "<<ivec.size()
<<"elements "<<sum
<<"average "<<average<<endl;
return 0;
}
14
//---------------------------------------------------------------------------
#include<iostream>
#include<vector>
#include<string>
using namespace std;
//---------------------------------------------------------------------------
int main()
{
const int array_size=120;
int la[array_size];
int ival,icnt=0;
while(cin>>ival&&icnt<array_size){
la[icnt++]=ival;
}
int sum=0;
for(int i=0;i<array_size;i++){
sum+=la[i];
}
int average=sum/array_size;
cout<<array_size
<<"\n"<<sum
<<"\n"<<average<<endl;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include<iostream>
#include<vector>
#include<string>
#include<fstream>
#include<algorithm>
using namespace std;
//---------------------------------------------------------------------------
int main()
{
ifstream in_file ("D:\inputfile.txt");
ofstream out_file("D:\outputfile.txt");
if(!in_file){
cerr<<"unable to open the inputfile" ;
}
if(! out_file){
cerr<<"unable to open the outputfile" ;
}
string word;
vector<string> text;
while(in_file>>word)
{
text.push_back(word);
}
cout<<"unsort file";
for(int i=0;i<text.size();++i)
{
cout<<text[i]<<" "<<endl;
}
cout<<"sort file";
sort(text.begin(),text.end());// sort the vector
for(int i=0;i<text.size();++i)
{
out_file<<text[i]<<" "<<endl;
}
}