1.學習了文件輸出後,看了c++ primer plus的例6.15.,有些不懂的註釋出來,便於以後學習。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char automobile[50];
int year;
double a_price;
double b_price;
ofstream outFile;
outFile.open("E:\\grade2017.txt",ios::out);//和書上不同,規定了輸出文件的路徑
cout<<"enter the make and model of automobile"<<endl;
cin.getline(automobile,50);
cout<<"enter the model year"<<endl;
cin>>year;
cout<<"enter the original asking price:";
cin>>a_price;
b_price=a_price*0.9;
//利用cout在屏幕上顯示出結果
cout<<fixed;
cout.precision(2);
cout.setf(ios_base::showpoint);
cout<<"make and model:"<<automobile<<endl;
cout<<"year:"<<year<<endl;
cout<<"was asking price:"<<a_price<<endl;
cout<<"Now asking price:"<<b_price<<endl;
//利用outFile輸出文件
outFile<<fixed;//用一般形式輸出字浮點數
outFile.precision(2);//表示兩位小數點輸出
outFile.setf(ios_base::showpoint);//強制顯示小數點輸出
outFile<<"make and model:"<<automobile<<endl;
outFile<<"year:"<<year<<endl;
outFile<<"was asking price:"<<a_price<<endl;
outFile<<"Now asking price:"<<b_price<<endl;
//切記關閉文件
outFile.close();
return 0;
}
2.學習cout.self 和cout.precision()
這兩個就是格式控制的~ostream成員函數裏面的,也可以用輸出流操作符來控制,都一樣的~附給你一些看看~
其中cout.setf跟setiosflags一樣的,cout.precision跟setprecision一樣~
#include <iomanip>
這裏面iomanip的作用比較多:
主要是對cin,cout之類的一些操縱運算子,比如setfill,setw,setbase,setprecision等等。它是I/O流控制頭文
件,就像C裏面的格式化輸出一樣.以下是一些常見的控制函數的:
dec 置基數爲10 相當於"%d"
hex 置基數爲16 相當於"%X"
oct 置基數爲8 相當於"%o"
setfill(c) 設填充字符爲c
setprecision(n) 設顯示小數精度爲n位
setw(n) 設域寬爲n個字符
這個控制符的意思是保證輸出寬度爲n。如:
cout<<setw(3)<<1<<setw(3)<<10<<setw(3)<<100; 輸出結果爲
1 10100 (默認是右對齊)當輸出長度大於3時(<<1000),setw(3)不起作用。
setioflags(ios::fixed) 固定的浮點顯示
setioflags(ios::scientific) 指數表示
setiosflags(ios::left) 左對齊
setiosflags(ios::right) 右對齊
setiosflags(ios::skipws 忽略前導空白
setiosflags(ios::uppercase) 16進制數大寫輸出
setiosflags(ios::lowercase) 16進制小寫輸出
setiosflags(ios::showpoint) 強制顯示小數點
setiosflags(ios::showpos) 強制顯示符號
舉例:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout<<12345.0<<endl;//輸出"12345"
cout<<setiosflags(ios::fixed)<<setprecision(3)<<1.2345<<endl;輸出"1.235"
cout<<setiosflags(ios::scientific)<<12345.0<<endl;//輸出"1.234500e+004
"
cout<<setprecision(3)<<12345.0<<endl;//輸出"1.235e+004 "
return 0;
}