C ++ primer learning notes (6.0) Statement

Source: Internet
Author: User
Tags bitset

6.1 simple statements

Empty statement; a semicolon // irrelevant null statement is not harmless

6.2 statement

Definition or declaration of objects or classes

6.3 compound statement (Block)

Block indicates a scope

For example, the while loop does not end with a semicolon.


6.4 statement Scope

Variables defined in conditional expressions must be initialized. This condition tests the value of the initialization object.

6.5if statement

if(a>b){/**/}else if(a=b)/*   */else /*    */

Pay attention to the issue of hanging else

Programming style suggestion: Always use curly brackets after if


6.6switch statement

The value of each case label must be a constant expression.

Const int val;

........

Case VAL: // OK

#include<iostream>#define FAIL 0; #define TRUE 1;using namespace std;int main(){char ch;int acnt=0,bcnt=0,ccnt=0,cnt=0;while(cin>>ch){switch(ch){  case 'a':      ++acnt;      break;  case 'b':      ++bcnt;      break;  case 'c':      ++ccnt;      break;  default:      ++cnt;  }}    cout<<"the number of a is"<<endl<<acnt<<endl; cout<<"the number of b is"<<endl<<bcnt<<endl; cout<<"the number of c is"<<endl<<ccnt<<endl;cout<<"the number of others is"<<endl<<cnt<<endl; return TRUE;}

Exercise 6.7

// Count the number of vowels # include <iostream> # include <string> using namespace STD; int main () {char ch; int CNT = 0; while (CIN> CH) {Switch (CH) {Case 'A': Case 'E': Case 'I ': case 'I': Case 'O': Case 'U': ++ CNT; default :;}} cout <"the number of vowel is" <Endl <CNT <Endl; return 0 ;}

// Modify the vowel statistical program so that it can count the number of FF, FL, and Fi Dual Characters

#include<iostream>using namespace std;int main(){char currch,prech='\0';int ffcnt=0,ficnt=0,flcnt=0;while(cin>>currch){if(prech=='f')switch(currch){case 'f':  ++ffcnt;  break;case 'l':  ++flcnt; case 'i':   ++ficnt;   break;   }prech=currch;}cout<<"The number of \'ff\' is "<<ffcnt<<endl;cout<<"The number of \'fi\' is "<<ficnt<<endl;cout<<"The number of \'fl\' is "<<flcnt<<endl;} 


6.7while statement

Variables defined in a loop must go through the creation and revocation processes in each loop.

Exercise 6.12

# Include <iostream> # include <string> using namespace STD; int main () {int currcnt = 1, maxcnt = 1; // define some counters: String prestr = "\ 0", currstr = "\ 0"; string repstr; // string cout with the most repeated Times <"input some strings: "<Endl; while (CIN> currstr) {If (prestr = currstr) currcnt ++; else {If (currcnt> maxcnt) {maxcnt = currcnt; repstr = prestr;} currcnt = 1;} prestr = currstr;} // process the case where the last value is the maximum value. If (currcnt> maxcnt) {maxcnt = currcnt; repstr = Cu Rrstr;} If (maxcnt> 1) {cout <"Repeat word is" <repstr <", and the number of it is" <maxcnt <Endl ;} else cout <"there is no repeat word! "<Endl; return 0 ;}

How to exit while (CIN> CH)

 

When the input stream ends, it cannot contain any character before ^ Z (except press Enter). Otherwise, ^ Z cannot end the stream.

Method: Press enter, CTRL + Z on the new line, and press Enter. It is invalid if Ctrl + Z is entered and then press Enter.
Cause:
The input buffer is a row buffer. After entering a string of characters on the keyboard and pressing enter, these characters are first sent to the input buffer for storage. Every time you press the Enter key, Cin. Get () checks whether readable data exists in the input buffer. Cin. get () also checks whether there are Ctrl + Z or Ctrl + D keys on the keyboard as the stream stop sign. There are two ways to check the result: blocking and non-blocking.

Blocking Check means that the CTRL + z combination key is used only after the Enter key is pressed, the non-blocking mode refers to the method of responding immediately after pressing CTRL + D. If you have entered characters from the keyboard before pressing CTRL + D, CTRL + D serves as a carriage return, that is, sending these characters to the input buffer for reading, in this case, CTRL + d no longer serves as the stream Terminator. If you do not have any keyboard input before pressing CTRL + D, CTRL + D indicates the end of the stream.

In Windows, blocking-type ctrl + Z and non-blocking-type ctrl + D are usually used in Unix/Linux systems. The main user is in windows, so the blocked Ctrl + Z is used to mark the end of the stream.

This blocking method has one feature: it is possible to detect whether Ctrl + Z is pressed before pressing the carriage return. Another feature is that if there is readable data in the input buffer, CTRL + Z will not be detected (because there is data to be read, it cannot be considered at the end of the stream ). Another thing we need to know: Ctrl + z does not produce a common ASCII code value, that is, it does not produce a character, therefore, it is not stored in the input buffer as other characters entered from the keyboard. After understanding these points, you can explain the questions raised by the landlord.

After entering ABCD ^ Z on the keyboard and pressing enter, it will be handled in the Windows system as follows: Due to the press ENTER function, the previous ABCD and other characters will be sent to the input buffer (Note: As mentioned above, ^ Z does not generate characters, so it is not stored in the input buffer, and there is no ^ Z in the buffer ). In this case, Cin. Get () detects that data already exists in the input buffer (so it no longer checks whether ^ Z input exists), and reads the corresponding data from the buffer. If all the data is read, the input buffer is empty again, and CIN. Get () waits for the new input. It can be seen that even if ^ Z is pressed, the stream will not end because there are other input characters (ABCD) before this.

Therefore, the input stream end condition is: ^ Z cannot have any character input (except press Enter), otherwise ^ Z cannot end the stream.

Reference http://www.2cto.com/kf/201202/119312.html

6.8for loop statement

For (INT I = 0, K = 0; I <= 10; ++ I) OK

For (INT I = 1, Long U = 1.221; I <= 10; I ++) erro error, initialization can only initialize one type


6.9do while statement

Unlike the while statement, the do while statement always ends with a semicolon.

Exercise 6.18

# Include <iostream> # include <string> using namespace STD; string max (string & A, string & B); int main () {string str1, str2, str3; cout <"Please input two strings:" <Endl; do {CIN> str1> str2; cout <max (str1, str2) <"is bigger. "<Endl; cout <" Please input two strings: "<Endl; cout <" continue? Y/N "<Endl; CIN> str3;} while (str3 [0] = 'y'); // string NO = comparison operator, therefore, use the first element to compare} string max (string & A, string & B) {if (a <B) return B; else return ;}

6.10break statement

The break statement is used to end the recent while, do while, for, or switch statements.

Exercise 6.20

# Include <iostream> # include <string> using namespace STD; int main () {string str1 = "\ 0", str2; int CNT = 1; // countcin> str1; while (CIN> str2) {If (str1 = str2) {cout <"Duplicate words:" <str2 <Endl; ++ CNT; break;} elsestr1 = str2;} If (CNT = 1) {cout <"No duplicate words" <Endl; return 0;} elsereturn 0 ;}

6.11continue statement

It only ends the iteration of the loop statement.

Exercise 6.21

# Include <iostream> # include <string> using namespace STD; int main () {string str1 = "\ 0", str2; int CNT = 1; // countcin> str1; while (CIN> str2) {If (str2 [0] <= 'Z' & str2 [0]> = 'A' & str1 = str2) {cout <"the duplicate words starting with an uppercase letter are:" <str2 <Endl; ++ CNT; break;} elsestr1 = str2 ;} if (CNT = 1) {cout <"no words starting with an uppercase letter and repeating" <Endl; return 0;} elsereturn 0 ;}

6.12goto statement

The GOTO statement is not recommended.

The GOTO statement cannot jump forward across the variable definition statement. If necessary, the definition should be placed in the block statement.


6.13try block and Exception Handling

Throw expression

If (! Item1.same _ ISBN (item2 ))

Throw runtime_erro ("dsta must refer to same ISBN .");

Throw uses a runtime_error type object. runtime_error is one of the exception classes in the standard library, which is defined in the stdexcept header file.

Try Block

Try {

Program-statements

} Catch (exception-specifier ){

Handler-statements

} Catch (exception-specifier ){

Handler-statements

}//....

Exercise 6.23

#include<iostream>#include<bitset>using namespace std;int main(){  bitset<100> bs;  for(size_t ix=0;ix!=bs.size();++ix)     bs[ix]=1;  bs.to_ulong();  return 0;   }

Exercise 6.34

#include<iostream>#include<bitset>#include<stdexcept>using namespace std;int main(){  bitset<100> bs;  for(size_t ix=0;ix!=bs.size();++ix)     bs[ix]=1; try{  bs.to_ulong(); }catch (runtime_error err){ cout<<err.what()<<endl; }  return 0; }

Standard exception

The standard library exception class is defined in the following four header files

1. Exception header file: defines the most common standard exception class. Its Class Name is exception.

Only notifications of exceptions are generated, but no more information is provided.

2. The stdexcept header file defines the following common exception classes:

Function function or function

Exception

Runtime_error: error detected only during running

Range_error: the error message returned exceeds the valid value range.

Overflow_error: computing Overflow

Underflow_error: computing Overflow

 

Logic_error logical error: problems detected before running

Domain_error logic error: The result value of the parameter does not exist.

Invalid_argument logical error: Inappropriate Parameter

Length_error logic error: an object that exceeds the maximum length of this type is attempted.

Out_of_range logical error: Use a value out of the valid range

 

3. The new header file defines the bad_alloc exception type and provides the exception thrown by new because the memory cannot be allocated.

4. The type_info header file defines the bad_cast exception type. To use type_info, the header file must contain the typeinfo header file)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.