c++ 控制台I/O

來源:互聯網
上載者:User

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");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.