美文网首页
C++ 输入输出,字符串和面向对象

C++ 输入输出,字符串和面向对象

作者: CaptainRoy | 来源:发表于2018-06-09 21:39 被阅读0次
    • 基本输出
    #include <iostream>
    
    using namespace std;
    
    int main(int argc, const char * argv[]) {
        
        cout << "Hello, World! \n";
        cout << "Hello C++ " << endl; // endl 代替 \n
        
        return 0;
    }
    
    • 输入输出
    /*
    提示输入一个整数,该整数分别以八进制,十进制,十六进制打印出来
     */
    int x = 0;
    cout << "请输入一个整数:" << endl;
    cin >> x;
    cout << "八进制 : " << oct << x << endl;
    cout << "十进制 : " << dec << x << endl;
    cout << "十六进制 : " << hex << x << endl;
        
    /*
    提示输入一个布尔值(0或1) 以布尔方式打印出来
    */
    bool y = false;
    cout << "输入一个布尔值(0,1): "<<endl;
    cin>>y;
    cout<<"输入的布尔值为: "<<boolalpha<<y<<endl;
    
    • 栈和堆的实例化对象
    class Coordinate
    {
    public:
        int x;
        int y;
        void printX()
        {
            cout << x << endl;
        }
        
        void printY()
        {
            cout << y << endl;
        }
    };
    
    // 栈实例化对象
    Coordinate coor;
    coor.x = 10;
    coor.y = 20;
    coor.printX();
    coor.printY();
        
    // 堆实例化对象
    Coordinate *pCoor = new Coordinate();
    pCoor->x = 100;
    pCoor->y = 200;
    pCoor->printX();
    pCoor->printY();
    
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Student
    {
    public:
        string name;
        int age;
        
        void introduce()
        {
            cout  << "我的名字是 :"+name+" 今年" << age << "岁"<<endl;
        }
    };
    
    int main(int argc, const char * argv[]) {
        
        Student *s = new Student();
        s->name = "Roy";
        s->age = 18;
        s->introduce();
        
        
        return 0;
    }
    
    • 字符串 #include <string>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main(int argc, const char * argv[]) {
        
        string name = "Roy";
        string hello = "Hello";
        string greet = name + hello;
        cout << greet << endl;
        
        return 0;
    }
    
        string name;
        cout << "请输入您的名字: "<<endl;
        cin >> name; // Roy
        cout << "Hello "+name << endl; // Hello Roy
        cout << "您的第一个字母是: "<<name[0]<<endl; // 您的第一个字母是: R
    

    相关文章

      网友评论

          本文标题:C++ 输入输出,字符串和面向对象

          本文链接:https://www.haomeiwen.com/subject/rasxeftx.html