C++編程基礎練習


注:本文練習題均出自《Essential C++》第一章

練習1,1 從一個簡單程序開始

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

int main()
{
    string user_name;
    cout << "Please enter your first name :";
    cin >> user_name;
    cout << '\n'
         << "Hello,"
         << user_name
         << "... and goodbye!\n";
         
    return 0;
}

 

1,將string頭文件注釋掉,重新編譯這個程序,會發生什么事?

目前還沒有發現會發生什么事。

 

2,將using namespace std注釋掉,重新編譯,會發生什么事?

 

3,將函數名main()改為my_main(),然后重新編譯,有什么結果?

 

練習1.2

將上述程序的內容進行擴充(1)要求用戶同時輸入名字(first name)和姓氏(last name);(2)修改輸出結果,同時打印姓氏和名字。

 

1,定義兩個string對象:string first_name,last_name;

2,定義一個vector,儲存兩個string對象:vector<string> usr_name(2);

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

int main()
{
    string first_name,last_name;
    cout << "Please enter your first name :";
    cin >> first_name;
    cout << "hi, " << first_name
         << "Please enter your last name: ";
        
    cin >> last_name;
    cout << '\n';
    cout << "Hello, "
         << first_name << ' ' << last_name
         << "... and goodbye!\n";

    return 0;
}

 

練習1.3

編寫一個程序,能夠詢問用戶的姓名,並讀取用戶所輸入的內容。請確保用戶輸入的名稱長度大於兩個字符。如果用戶的確輸入了有效名稱,就響應一些信息。

請以兩種方式實現:第一種使用C-style字符串,第二種使用string對象。

1,C-style字符串

首先,我們必須決定user_name的長度;接下來,利用標准庫的strlen()函數獲得user_name的長度,cstring頭文件中有strlen()的聲明。

如果用戶輸入的字符串長度大於之前已經輸入的字符,就沒有足夠的空間來存放終止字符(null字符)。為了防止這種事情的發生,我以iostream操縱符(manipulator)setw()保證不會讀入超過127個字符。由於用到了setw()操縱符,因此必須包含iomanip頭文件。

#include<iostream>
#include<iomanip>
#include<cstring>
using namespace std;

int main()
{
    const int nm_size = 128;  //必須分配一個大小固定的空間
    char user_name[nm_size];
    cout << "Please enter your name: ";
    cin >> setw(nm_size) >> user_name;
    
    switch(strlen(user_name))
    {
        case 127:
            cout << "That is a very big name,indeed --"
                 << "we may have needed to shorten it\n"
                 << "In any case,\n";
                 
        default:
            cout << "Hello, " << user_name
                 << " -- happy to make your acquaintance!\n";
            break;
     } 
     
     return 0;
 } 

 

2,string對象(推薦)

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

int main()
{
    string user_name;
    cout << "Please enter your name: ";
    cin >> user_name;
    
    switch(user_name.size()){
        case 0:
            cout << "Ah,the user with no name. ";
            break;
        
        case 1:
            cout << "A 1-character name? Hmm,have you read Kafka?: ";
            break;
        
        default:
            cout << "Hello, " << user_name
                 << "-- happy to make your acquaintance!\n";
            break;
    }
    return 0;
}

 

練習1.4

編寫一個程序,從標准輸入設備讀取一串整數,並將讀入的整數依次放到array及vector,然后遍歷這兩種容器,求取數值綜合。將總和及平均值輸出至標准輸出設備。

 

兩者之間的區別

  • array的大小必須固定,vector可以動態地隨着元素的插入而擴展儲存空間。
  • array並不儲存自身大小。
//使用vector 

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

int main()
{
    vector<int> ivec;
    int ival,sum;
    while(cin >> ival)
        ivec.push_back(ival);
        
    for(int sum = 0,ix = 0;ix < ivec.size();++ix) //遍歷vector元素,一一累加 
        sum += ivec[ix];
    
    int average = sum / ivec.size();
    
    cout << "Sum of " << ivec.size()
         << " elements: " << sum
         << ". Average: " << average << endl;
}

 

//使用array 

#include<iostream>
using namespace std;

int main()
{
    const int array_size = 120;
    int ia[array_size],sum;
    int ival,icnt = 0;
    
    while(cin >> ival && icnt < array_size)
        ia[icnt++] = ival;
        
    for(int sum = 0,ix = 0;ix < icnt;++ix)
        sum += ia[ix];
        
    int average = sum / icnt;
    
    cout << "Sum of " << icnt
         << " elements: " << sum
         << ". Average: " << average << endl;
}

 

練習1.5

使用你最稱手的編輯工具,輸入兩行(或更多)文字並存盤。然后編寫一個程序,打開該文本文件,將其中每個字都讀取到一個vector<string>對象中。遍歷該vector,將內容顯示到cout。然后利用泛型算法sort(),對所有文字排序:

#include<algorithm>
sort( container.begin(),container.end() ); 

 

再將排序后的結果輸出到另一個文件。

 

#include<iostream>
#include<fstream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;

int main()
{
    string word;
    ifstream in_file("D:\\Documents\\text.txt");
    if(!in_file)
    {
        cerr << "oops! unable to open input file\n";
        return -1;
    }
    
    ofstream out_file("D:\\Documents\\text.sort");
    if(!out_file)
    {
        cerr << "oops! unable to open output file\n";
        return -2;
    }
    
    string world;
    vector < string > text;
    while(in_file >> word)
        text.push_back(word);
    
    int ix;
    cout << "unsorted text: \n";
    
    for(ix = 0;ix < text.size();++ix)
        cout << text[ix] << ' ';
    cout << endl;
    
    sort(text.begin(),text.end());
    
    out_file << "sorted text: \n";
    for(ix = 0;ix < text.size();++ix)
        out_file << text[ix] << ' ';
    out_file << endl;
    
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM