1. 顯示字串,讀取字串
#include <iostream>
using namespace std;
void get_filename(string& filename)
{
cout << endl;
cout << "Enter file name to process." << endl;
cin >> filename;
cout << endl;
}
引入的標頭檔:
#include <iostream>
using namespace std;
2. 顯示字串,讀入整形數字
#include <iostream>
using namespace std;
void get_level( int& level)
{
do
{
cout << endl;
cout << "Please choose an depth (2-12): ";
cin >> level;
}while ( level > 12 || level <2);
}
3. 控制台條件輸入
#include <iostream>
using namespace std;
do
{
cout << endl;
cout << "Please enter the hash table size(more than 6500): ";
cin >> resize;
}while ( resize < 6500 );
4. getline 方法
#include <iostream>
char s[11];
cin.getline(s,11);
cin.clear();
string line;
getline(cin,line);
5.格式輸出
#include <sstream>
ostringstream oss;
oss << ”pointer->word“ ;
oss<< ”pointer2->word“ ;
string aline = oss2.str();
cout << aline;
oss.str(" "); // oss清空,是想象中的 oss.clear();
6. C++設定輸出小數位元方法
浮點數的輸出一共有三種模式:普通、固定小數、科學記號標記法
後兩種分別對應格式標記 ios::fixed, ios::scientific 。都不設的話就是普通模式,即自動選擇小數或科學記號標記法(看哪種佔用寬度小)
設定後兩種模式需要用 fstream 的成員函數 fout.setf(flag)
要固定2位小數,只要選擇 fixed 模式並設定精度為 2 即可,
另外,ios::showpoint 根據精度設定顯示小數點和末尾的零
cout.width() 設定輸出欄位的寬度《21天學通C++》P435;
#include<fstream>
using namespace std;
int main(){
ofstream fout("out.txt");
fout.setf(ios::fixed, ios::floatfield); // 設定為 fixed 模式,以小數點表示浮點數
fout.precision(2); // 設定精度 2
7. 控制台暫停
#include <cstdlib>system("pause");