Tuesday, December 13, 2005
C++ Tutorial
- C++ Tutorial
- C++ StrTok
- Gary's Note
- Microsoft MSDN developer
- Pointer
Pointer功能強大且好用,但在使用之前,先要initialized,不然它會指向任意處,會造成電腦記憶體不預期的問題。
pointer is initialized to point to a specific memory address before it is used. If this was not the case, it could be pointing to anything. This can lead to extremely unpleasant consequences to the computer. You should always initialize pointers before you use them.
#includeusing namespace std; int main() { int x; int *p; p = &x; cin>> x; cin.ignore(); cout<< *p <<"\n"; cin.get(); } int *ptr = new int;
It initializes ptr to point to a memory address of size int (because variables have different sizes, number of bytes, this is necessary). The memory that is pointed to becomes unavailable to other programs. This means that the careful coder should free this memory at the end of its usage. Allocate完區塊的memory,在程式執行完後,必須要釋 放memory(就是透過delete ptr;),然後指定此pointer為null pointer。
After deleting a pointer, it is a good idea to reset it to point to 0. When 0 is assigned to a pointer, the pointer becomes a null pointer, in other words, it points to nothing.
String Manipulation
<string.h> char * strtok ( const char * string, const char * delimiters );
Sequentially truncate string if delimiter is found. If string is not NULL, the function scans string for the first occurrence of any character included in delimiters. If it is found, the function overwrites the delimiter in string by a null-character and returns a pointer to the token, i.e. the part of the scanned string previous to the delimiter.
After a first call to strtok, the function may be called with NULL as string parameter, and it will follow by where the last call to strtok found a delimiter. delimiters may vary from a call to another.
Parameters:
- string: Null-terminated string to scan.
- separator: Null-terminated string containing the separators.
- Return Value: A pointer to the last token found in string. NULL is returned when there are no more tokens to be found.
#include <stdio.h>
#include <string.h>
int main ()
{ char str[] ="This is a sample string,just testing.";
char * pch;
printf ("Splitting string \"%s\" in tokens:\n",str);
pch = strtok(str," ");
while (pch)
{ printf ("%s ",pch);
pch = strtok(NULL, ",."); }
return 0; }
/* Splitting string "This is a sample string,just testing." in tokens:
This is a sample string just testing */
函式strtok(str, Token);會回傳string segment(字串片段)