C 程式設計基礎練習

2022-02-01 00:46:21 字數 2455 閱讀 3135

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

#include#include

using

namespace

std;

intmain()

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

3,將函式名main()改為my_main(),然後重新編譯,有什麼結果?

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

#include#include

using

namespace

std;

intmain()

編寫乙個程式,能夠詢問使用者的姓名,並讀取使用者所輸入的內容。請確保使用者輸入的名稱長度大於兩個字元。如果使用者的確輸入了有效名稱,就響應一些資訊。

請以兩種方式實現:第一種使用c-style字串,第二種使用string物件。

首先,我們必須決定user_name的長度;接下來,利用標準庫的strlen()函式獲得user_name的長度,cstring標頭檔案中有strlen()的宣告。

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

#include#include

#include

using

namespace

std;

intmain()

return0;

}

#include#include

using

namespace

std;

intmain()

return0;

}

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

兩者之間的區別

//

使用vector

#include

#include

using

namespace

std;

intmain()

//

使用array

#include

using

namespace

std;

intmain()

使用你最稱手的編輯工具,輸入兩行(或更多)文字並存檔。然後編寫乙個程式,開啟該文字檔案,將其中每個字都讀取到乙個vector物件中。遍歷該vector,將內容顯示到cout。然後利用泛型演算法sort(),對所有文字排序:

#includesort( container.begin(),container.end() );
再將排序後的結果輸出到另乙個檔案。

#include#include

#include

#include

#include

using

namespace

std;

intmain()

ofstream out_file(

"d:\\documents\\text.sort");

if(!out_file)

string

world;

vector

< string >text;

while(in_file >>word)

text.push_back(word);

intix;

cout

<< "

unsorted text: \n";

for(ix = 0;ix < text.size();++ix)

cout

<< text[ix] << '';

cout

<

sort(text.begin(),text.end());

out_file

<< "

sorted text: \n";

for(ix = 0;ix < text.size();++ix)

out_file

<< text[ix] << '';

out_file

<

return0;

}

C 程式設計基礎練習,入門必備練手

練習1,1 從乙個簡單程式開始 1,將string標頭檔案注釋掉,重新編譯這個程式,會發生什麼事?目前還沒有發現會發生什麼事。2,將using namespace std注釋掉,重新編譯,會發生什麼事?3,將函式名main 改為my main 然後重新編譯,有什麼結果?練習1.2 將上述程式的內容進...

C 程式設計基礎練習,入門必備練手

練習1,1 從乙個簡單程式開始 1,將string標頭檔案注釋掉,重新編譯這個程式,會發生什麼事?目前還沒有發現會發生什麼事。2,將using namespace std注釋掉,重新編譯,會發生什麼事?3,將函式名main 改為my main 然後重新編譯,有什麼結果?練習1.2 將上述程式的內容進...

Java基礎程式設計練習

練習題 輸入乙個3位的整型數,輸出其百位 十位及個位數 public class test1 練習題 判斷乙個數是否是素數 public class test2 if m 1 else if m i 練習題 百分制轉成等級制 public class test3 char ch switch m 1...