Improvement of C ++ (1)

Source: Internet
Author: User
Tags control characters

Improvement of C ++ (1)
Address: Workshop

Int x = 1024;

C ++ provides two initialization methods:

Copy-initialization)

For example, int x = 1024;

Direct-initialization ):

For example, int x (1024 );

Note:

① Initialization is not a simple assignment. Initialization refers to declaring a variable or object and assigning an initial value. The assignment refers to overwriting the current value of the variable or object with a new value.

② The direct initialization syntax is more flexible and more efficient

③ Initialization of built-in type variables there is almost no difference between the two types of initialization for class type initialization, sometimes only use direct initialization (discussed later)

④ The two initialization methods can be mixed (see the following example)

Example of combined initialization:

#include <iostream>using namespace std;int main(){    double salary = 9999.99, wage(salary + 0.01);    cout<<salary<<" "<<wage<<endl;    int interval,month = 8, day = 7, year(2008);    cout<<year<<":"<<month<<":"<<day<<":"<<endl;     system("PAUSE");    return 0;}
New I/O

C Language Input and Output:

Input and Output of C ++:

Input and Output of C ++: Faster first

# Include <iostream> using namespace std; int main () {int x; double y;/* The following statement is equivalent to printf ("enter two integers (separated by commas ): "); */cout <" enter two integers (separated by spaces): ";/* the following statements are equivalent to scanf (" % d % f ", & x, & y); */cin> x> y;/* the following statements are equivalent to printf ("x = % d, y = % f \ n", x, y); */cout <"x =" <x <", y =" <y <endl; system ("PAUSE"); return 0 ;}

C ++ input and output: cin, cout usage

Basic usage:

Cout <expression 1 <expression 2 <expression n;

Cin> variable 1> variable 2> Variable n;

For example:
cout<<"x + y ="<< x + y << "." << endl;cin >> x >> y;

[Note]

① One <output multiple data items

Cout <a, B, c <endl;/* Error */cout <a <B <c <endl;/* correct */

② Cin/cout can be divided into multiple lines for writing

cin>>a>>b   >>c;cout<<a<<b    <<c;

Example of cout usage:

#include <iostream>using namespace std;int main(){     cout << "This is a C++ program! " << endl;     cout << "This is"          << " a C++"          << "program!"          << endl;     system("PAUSE");     return 0;}

Examples of using cin:

int main(){        char  c1, c2;    int a;      float b;    cin >> c1 >> c2 >> a >> b;    cout << "c1 = " << c1 << endl         << "c2 = " << c2 << endl         << "a = " <<a << endl         << "b = " << b << endl;    system("PAUSE");    return 0; }

Cout and output control characters:

# Include <iostream> # include <iomanip> using namespace std; int main () {int x = 0; cout <"enter an octal INTEGER (start ):";
Cin> oct> x; The hexadecimal representation of cout <"x is:"

Output controller:

Note: If a controller is used, the program must contain the header file # include <iomanip>

Differences between types

Differences between types: bool type

 

Logical type

True

False

C

Not provided

Non-0

0

C ++

Bool

True

False

Note:

1) The bool type has only two valid values: true and false.

2) The default output is 0 or 1.

3) Use boolalpha to change the default output mode. noboolalpha can restore the default output mode.

#include <iostream>using namespace std;int main(){    bool bval1 = 1 < 2;    bool bval2 = true;    bool bval3 = false;    bool bval4 = 4;    bool bval5 = 0;    cout << "bval1=" << bval1 << endl;    cout << "boolalpha bval1=" << boolalpha << bval1 << endl;    cout << "noboolalpha bval1=" << noboolalpha << bval1 << endl;    cout << "bval2=" << bval2 << endl;    cout << "bval3=" << bval3 << endl;    cout << "bval4=" << bval4 << endl;    cout << "bval5=" << bval5 << endl;    system("PAUSE");    return 0;}

Difference in types: string class

#include <iostream>#include <string>using namespace std;int main(){    string name = "student";    string address = "Hebei... ...";    cout << name << address <<endl;    return 0;}

Definition and initialization of a string object:

Method of initializing a string object

String s1;

Default constructor. s1 is an empty string.

String s2 (s1 );

Initializes s2 as a copy of s1.

String s3 ("value ");

Initialize s3 with the string literal value

String s4 (n, 'C ')

Initialize s4 to n copies of the character 'C'

#include <iostream>#include <string>using namespace std;string s0;int main( ){    string s1;    //string s2 = "hello world!";    string s2("hello world!");    //string s3 = s2;    string s3(s2);    string s4(5, 'r');    cout << "s0=" <<s0 <<endl;    cout << "s1=" <<s1 <<endl;    cout << "s2=" <<s2 <<endl;    cout << "s3=" <<s3 <<endl;    cout << "s4=" <<s4 <<endl;    system("PAUSE");    return 0;}

Read and Write of string objects: Use cin and cout to read and write string objects.

Note:

All leading spaces, tabs, and carriage returns are ignored in cin.

Do not receive strings containing Spaces

String I/O:

#include <iostream>#include <string>using namespace std;int main(){    string s;    cin >> s;      //hello world!    cout << s <<endl;  //hello    system("PAUSE");    return 0;}

String:

#include <iostream>#include <string>using namespace std;int main(){    string word;    while(cin >> word)        cout << word << endl;        system("PAUSE");    return 0;}

Read and Write of string objects: Use getline to read the entire line of text (including spaces ).

#include <iostream>#include <string>using namespace std;int main(){    string line;    while(getline(cin, line))                          cout << line << endl;     system("PAUSE");     return 0;}

Note:

The first parameter of getline is usually cin, and the second parameter is a string object.

Read from the next row of the input data. It can read any character.

Getline () uses the carriage return as the end character (line break is not accepted)

Getline () does not ignore the leading carriage return. if the first one is a line break, it is set to an empty string.

String object operations, with: string s, s1;

String operation

S. empty ()

If s is an empty string, true is returned; otherwise, false is returned.

S. size ()

Returns the number of characters in s.

S [n]

Returns the character whose position is n in s, starting from 0.

S1 + s2

Concatenates two strings into a new string and returns the new string.

S1 = s2

Replace the content obtained from s1 with a copy of s2.

V1 = v2

Returns true if the values are equal. Otherwise, returns false.

! = <=> =

Keep these operations in common, such as: s! = S2;

Note:

1. The return type of size () is not int but string: size_type. We recommend that you do not assign the return value of size () to the int variable.

string s2 = "hello";string::size_type count = s2.size();
2. When two string objects +, the plus and right operands of the + operator must have at least one string
#include <iostream>#include <string>using namespace std;int main(){    string s1 = "hello";    string s2 = "world";    string s3 = s1  + ",";    string s4 = "hello" + "world ";  //error    string s5 = "hello" + s2 + "world" ;    system("PAUSE");    return 0;}
3. When the string object subscript operation is performed, any unsigned integer value can be used as the subscript, but the actual type of the subscript is string: size_type.

4. The string subscript operation can be used as the left value.

int main(){      string str = "student";    cout << str << endl;    for(string::size_type ix = 0; ix!=str.size(); ++ix)             str[ix] = 'x';    cout << str << endl;        system(" PAUSE ");    return 0;}

Differences about types: Enumeration

C ++ improves enumeration:

① You can define enumeration variables in C ++ without using enum.

Enum weekday {sun, mon, tue, wed, thu, fri, sat}; weekday w; // enum is omitted

② Unnamed enumeration: The Enumeration type name and variable are not given. When an enumeration element is a symbolic constant

enum{min = 0, max = 100};int x = min, arr[max];
... ...

Difference in related types: union

C ++ extension of union:

① Unknown Union: a Union without a consortium type name or variable name

#include <iostream>using namespace std;int main(){    union {        char c;        int i;        double d;    };    c = 'a';    cout << c << endl;    return 0;}

② Union is not required for defining federated variables.

#include <iostream>using namespace std;union test{      char c;    int i;    double d;};int main(){    test m = {'a'};    cout << m.c << endl;    return 0;}

Difference in types: struct

C ++ extends the struct

① Struct variables can be defined without struct

struct  point{    double x;    int a;};point  p;

② A member can contain function definitions

Struct point {double x, y; // data member void setvalue (double a, double B) // member function {x = a; y = B ;}};

 

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.