C++ Noticing Points

**************************27/4/2015*******************


For ACIS220 assignment 1 & 2 there are some points for noticing:

1. strlen(STR) & sizeof(STR)

   Code:

-------------------------------------------------------------------------------------------------------------

 //string Test_String("Default Empty");

char Example[6] = { 'a', 'b', 'c', 'd' };

int valueofsize = -1;
int valueoflength = -1;
valueofsize = sizeof(Example);
valueoflength = strlen(Example);
cout << "the value of sizeof is " << valueofsize << endl;
cout << "the value of sizeof is " << valueoflength << endl;

----------------------------------------------------------------------------------------------------------------

   strlen() works as: 

         Starting from the beginning of the string/array and count until the very first '\0' met. So ideally, if there is any '\0' inside an array\string, the return value of strlen() can be very tricky. If there is not any '\0' in the middle of such data structures, the function just will produce the real length of an array/string.

   sizeof() works as:

         Just try searching the whole memory space allocated to such array/string. So it will produce the pre-allocated memory space in bytes as the return type, ignoring what currently is store in this array/string.



2. String Rewrite

    String in C++ is absolutely rewrite-able.  After an implicit declaration of string(without specify its length), string can be rewritten into any length. However, there do exist certain maximum length of the string type, don't over-range it. 

    The thing happen when you declare a string:

         The compiler will allocate a piece of memory space for the new string with maximum size and return the pointer points to this piece of memory space to the user. Each time you manipulate this new string, you are actually calling the pointer. And in this way, the compiler takeover the stack management stuffs instead of the user himself. Thus, indeed simplified a lots of memory management work and risks.

      

    code:

--------------------------------------------------------------------------------------------------------------------------------------

string Test_String("Default Empty");

 //equal to string Test_String="Default Empty"
Test_String = "This is a muuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuch longer string than the previouse one!";
cout << Test_String << endl;
Test_String = "Shorter!";
cout << Test_String << endl;

--------------------------------------------------------------------------------------------------------------------------------------

 


**************************29/4/2015*******************   

3. Loop termination condition(especially flag value problem)

         Each time you quite one loop, the loop termination condition must be met.

Like:

----------------------------------------------------------

//pseudo code

  for(int i=0;i<10;i++){

     do something...

}

----------------------------------------------------------

         Once you quite above loop, the value of i should be i=10 instead of i=9;

         The same thing happens to while loop and do-while loop.

         However, even if there initialed condition of do-while loop meets the termination condition, the do-while will still run at least on iteration! Because of the termination check point is at the end of the while statement, and the do statement will automatically run at least once.

         The for and while loop will not have this feature, they will quite immediately once the termination condition triggered. And possibly, the loop never starts actually.

Like:

---------------------------------------------------------

//pseudo code

int i=-1;

  do{

     i=i-1;

}

while(i>=0);

output the value of i;

---------------------------------------------------------

        output should be: i=-2.




4. The difference between calling ' ' and " "       

In a word:

      The single quote means there is a character between the quotes.  

      The double quote means there a string between the quotes.

The difference deeply rely behind this is:

       The compiler will automatically add a '\o' at the end of double quotes. That will force the contents within it to be a string with a certain end. Thus sometimes, the double quote can be used to assign value to a pointer or string. But single quote can just assign value to character variables like an element of an array of characters.

------------------------------------------------------------------

string newstring="This is a string!";

char char_array[5]={'a','b','c','d'}; 

------------------------------------------------------------------

5. ++n & n++

     First of all, these two notations have no difference in representing n=n+1. Such as:

---------------------------------------------------------------------------

for(int i=0,i<10,i++)

is just the same as:

for(int i=0,i<10,++i)

because they are all the simplification for:

for(int i=0,i<10,i=i+1)

-----------------------------------------------------------------------------

      Despite representing n=n+1, these two notations have various use in calculation for self-increment.

     However, in such kind of calculation, there exists very strict differences between them.

     Once you treat n++/++n as an operation factor(運算因子), they are totally different.

Like:

----------------------------------------------------------------

n=5;

i=n++;

----------------------------------------------------------------

output i=5; n=6;

----------------------------------------------------------------

n=5;

i=++n;

------------------------------------------------------------------------------------------------

output i=6;n=6;


From this example you can see:

       Once treated as an operation factor, the ++n/n++ becomes an union and the position of '++' sign refers to the self-increment is calculated before the whole union finished using as an operation factor or after that.

Meaning :

---------------------------------------------------------------------------

n=5;

i=n++;

----------------------------------------------------------------------------

has the same calculation order with

----------------------------------------------------------------------------

n=5;

i=n;

n=n+1/n++;

-----------------------------------------------------------------------------------------------

n=5;

i=++n;

-----------------------------------------------------------------------------

has the same calculation order with

-----------------------------------------------------------------------------

n=5;

n=n+1/++n;

i=n;

-------------------------------------------------------------------------------------------------

     The self-decrements notation: --n/n-- just have the exact same situation with this one.

     So please make sure you take the right order in using such self-increment or self-decrements notations.


 **************************30/4/2015*******************   

6. File I/O by calling input class

        Suppose we have such a text called "data.txt" as input file, it contains following words:

-----------------------------------------------------------

Fry: One Jillion dollars.
[Everyone gasps.]
Auctioneer: Sir, that's not a number.
数据读取, 测试 。

----------------------------------------

     Now, there are some methods realizing read/write operation from/to this file by calling fstream function which is contained in the fstream function library.

Reading from data.txt:

----------------------------------------------------------------------

  #include <iostream>
#include 
<fstream>
#include 
<string>

using namespace std;

//output an empty line
void OutPutAnEmptyLine()
{
    cout
<<"\n";
}



//read data from the file, Word BWord
//when used in this manner, we'll get space-delimited bits of text from the file
//but all of the whitespace that separated words (including newlines) was lost. 
void ReadDataFromFileWBW()
{
    ifstream fin(
"data.txt");  
    
string s;  
    
while( fin >> s ) 
    
{    
        cout 
<< "Read from file: " << s << endl;  
    }

}



//If we were interested in preserving whitespace, 
//we could read the file in Line-By-Line using the I/O getline() function.
void ReadDataFromFileLBLIntoCharArray()
{
    ifstream fin(
"data.txt"); 
    
const int LINE_LENGTH = 100
    
char str[LINE_LENGTH];  
    
while( fin.getline(str,LINE_LENGTH) )
    
{    
        cout 
<< "Read from file: " << str << endl;
    }

}



//If you want to avoid reading into character arrays, 
//you can use the C++ string getline() function to read lines into strings
void ReadDataFromFileLBLIntoString()
{
    ifstream fin(
"data.txt");  
    
string s;  
    
while( getline(fin,s) )
    
{    
        cout 
<< "Read from file: " << s << endl; 
    }

}



//Simply evaluating an I/O object in a boolean context will return false 
//if any errors have occurred
void ReadDataWithErrChecking()
{
    
string filename = "dataFUNNY.txt";  
    ifstream fin( filename.c_str());  
    
if!fin ) 
    
{   
        cout 
<< "Error opening " << filename << " for input" << endl;   
        exit(
-1);  
    }

}


int main()
{
    ReadDataFromFileWBW(); 

    OutPutAnEmptyLine(); 

    ReadDataFromFileLBLIntoCharArray(); 

    OutPutAnEmptyLine(); 

    ReadDataFromFileLBLIntoString(); 

    OutPutAnEmptyLine(); 

    ReadDataWithErrChecking(); 

    return 0;
}

---------------------------------------------------------------------------------------

         The output result is:

--------------------------------------------------------------------------------------

Read from file: Fry:
Read from file: One
Read from file: Jillion
Read from file: dollars.
Read from file: [Everyone
Read from file: gasps.]
Read from file: Auctioneer:
Read from file: Sir,
Read from file: that's
Read from file: not
Read from file: a
Read from file: number.
Read from file: 数据读取,
Read from file: 测试
Read from file: 。
 

Read from file: Fry: One Jillion dollars.
Read from file: [Everyone gasps.]
Read from file: Auctioneer: Sir, that's not a number.
Read from file: 数据读取, 测试 。

Read from file: Fry: One Jillion dollars.
Read from file: [Everyone gasps.]
Read from file: Auctioneer: Sir, that's not a number.
Read from file: 数据读取, 测试 。

Error opening  dataFUNNY.txt for input
Press any key to continue

-----------------------------------------------------------------------------------

   Some times you may find your function cannot read from the named file, and checking by is_open() function the return value always equal to 0. This means your program has some difficulties in finding the named file. Despite double checking the correct position of your text file, in VC++ you can also try clearly specify the location of the file and force your program finding it correctly.

   The way to do so is:

Project->Properties->Debugging->Working Directory

Replacing the "&project" under working directory for the full path where your project is located.

 

 

      In some rare cases, you may find your file is already opened but still you cannot read from that file. It may caused by "double open" statement. Meaning you may carelessly wrote more than file open sentence in your program opening the same file.

------------------------------------------------------------------------------------

#include <iostream>
#include <fstream>
using namespace std;


int main(){
//string name[20];
int score[3] = { 0, 0, 0 };
//You must recomment the "input.open("score.txt");" sentence out

        //or you still cannot read the file with double open
// input("score.txt") already openned the named file.
ifstream input("score.txt");
//input.open("score.txt");
for (int i = 0; i < 3; i++){
input >> score[i];
cout << "The score is " << score[i] << endl;
}
input.close();
system("pause");
return 0;
}

---------------------------------------------------------------------------------------





**************************02/5/2015*******************

7. >> & << 

     Despite for cout/cin and file input/output in C++, >> & <<  are also designed as a kind of shift operator. Just as introduced in your first few chapters about the C++ operators, >> & << are also commonly seen as shift operators. However in most cases you've met, they are treated as in/output notation for standard/file streams. Read the short introduction from Microsoft about the C++ operators, you will find out more about  >> & << as shift operators.

    点击打开链接


**************************03/5/2015*******************

8. Loops for array input and output especially multidimensional arrays.

    When you try to do anything to an array, make sure you are conscious about:

    1): Arrays & Multidimensional arrays are started from 0.

    2): Only loops can guarantee correct output for an array. But there are several ways initializing an array. 

    3): Do not try to read/write out of the range for an array!


9. Reference:

     Reference in C++ has strict rule for initialization. You can not declare a reference without initialization.  So each time you call a reference, you must initialize it immediately in the same sentence for declaration.

10. Constructor in class:

    1. If you write the function body of a class function outside the class declaration, remember to put ::

            

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值