第六章 分支語句和邏輯運(yùn)算符
1. 關(guān)于cin類用在測(cè)試語句中
判等語句:為了能夠防止程序員將
==
錯(cuò)誤的寫成賦值符=
尽爆,可以將判等表達(dá)式寫成value == varible
的形式。cin
作為輸入類可以用到測(cè)試表達(dá)式中,例如int num; while (cin >> num)
,其返回值為istream類,該類作為測(cè)試條件時(shí)自動(dòng)轉(zhuǎn)換為boolz值(如果正確輸入返回真,錯(cuò)誤輸入返回假,且標(biāo)記錯(cuò)誤后停止輸入旋炒,并把錯(cuò)誤的輸入值留在輸入緩存隊(duì)列中),即如果輸入的是數(shù)字签杈,則表達(dá)式cin >> num
返回true瘫镇,如果輸入的是字母等其它非數(shù)字鼎兽,則返回false,且置位錯(cuò)誤標(biāo)志铣除,停止輸入谚咬。此時(shí)需要利用cin.clear()
函數(shù)重置以重新接受新的輸入,且在再次輸入前尚粘,還需要?jiǎng)h除輸入隊(duì)列中的錯(cuò)誤字符择卦。測(cè)試表達(dá)式也可以寫成連續(xù)輸入的形式,例如cin >> num1 >> num2
:
<pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="c++" cid="n8" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> int num;
while (!(cin >> num)) //當(dāng)輸入的是非數(shù)字時(shí)郎嫁,cin返回false
{
cin.clear(); //重置cin
while (cin.get() != '\n')
continue; //刪除輸入隊(duì)列中的錯(cuò)誤輸入
cout << "please enter a number:" //提示重新輸入
}</pre>
2.關(guān)于邏輯運(yùn)算符
||
或運(yùn)算符的計(jì)算順序是從左至右的秉继,如果左邊的表達(dá)式為真,則計(jì)算結(jié)束泽铛,整個(gè)表達(dá)式取真尚辑;若左邊的表達(dá)式為假,才在產(chǎn)生完所有副作用后計(jì)算右邊的表達(dá)式盔腔。&&
或運(yùn)算符的計(jì)算順序也是從左至右的杠茬,如果左邊的表達(dá)式為假,則計(jì)算結(jié)束弛随,整個(gè)表達(dá)式取假瓢喉;若左邊的表達(dá)式為真,才在產(chǎn)生完所有副作用后計(jì)算右邊的表達(dá)式撵幽。邏輯非
!
的優(yōu)先級(jí)高于其它邏輯和算術(shù)運(yùn)算符灯荧;算術(shù)運(yùn)算符高于&&
和||
運(yùn)算符礁击;邏輯與&&
高于邏輯或||
運(yùn)算符盐杂。但為了便于閱讀代碼,最好還是用括號(hào)加以確定哆窿。C++確保程序從左至右進(jìn)行邏輯運(yùn)算链烈,并在能肯定結(jié)果后立刻停止。標(biāo)識(shí)符and挚躯、or强衡、not都是C++的保留字,但不是C的保留字码荔,所以在C中使用它們前需要包含頭文件
iso646.h
漩勤。
3.關(guān)于字符函數(shù)庫cctype
C++通過包含頭文件cctype
可以繼承C語言中的與字符相關(guān)的函數(shù)軟件包:
4. 輸入到文件
使用文件輸出的主要步驟:
包含頭文件:
#include <fstream>
,其定義了一個(gè)用于處理輸入的ofstream類缩搅。聲明std命名空間越败;使用編譯指令using或前綴std::。
聲明一個(gè)或多個(gè)ofstream對(duì)象硼瓣,并對(duì)其命名究飞。
將該ofstream對(duì)象同一個(gè)文件名關(guān)聯(lián)起來,方法之一就是用open()方法。
就像使用cout那樣使用該ofstream對(duì)象(如結(jié)合<<亿傅、endl媒峡、setf()、precision()等)葵擎,但在使用完畢后要用close()方法將其關(guān)閉谅阿。
雖然頭文件iostream提供了一個(gè)預(yù)先定義好的名為cout的ostream對(duì)象,但我們?cè)诓僮魑募r(shí)必須聲明自己的ofstream對(duì)象酬滤,并為其命名奔穿,將其同文件關(guān)聯(lián)起來。此后便可以像使用cout那樣使用它敏晤,所有可用于cout的操作和方法都可用于它贱田。
<pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="c++" cid="n37" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> #include <iostream>
include <fstream>
int main()
{
using namespace std;
ofstream outFile;
outFile.open("my.txt"); // 若文件存在,則打開并將其長(zhǎng)度截?cái)酁?嘴脾,否則創(chuàng)建它男摧。
outFile << "hello world!\n" << endl;
outFile.close();
char yourfilename[50];
int i = 10;
ofstream fout;
cin >> yourfilename;
fout.open(yourfilename);
fout << i;
fout.close();
return 0;
}</pre>
5. 使用文件輸出
必須包含頭文件fstream,其定義了一個(gè)用于處理輸入的ifstream類译打。
需要申明一個(gè)或多個(gè)ifstream變量(對(duì)象)耗拓,并以自己喜歡的方式對(duì)其進(jìn)行命名。
必須指明名稱空間std奏司。
需要將ifstream變量與文件關(guān)聯(lián)起來乔询。方法之一就是使用open()方法 。
使用is_open方法檢查文件是否成功打開韵洋,經(jīng)常會(huì)出現(xiàn)“指定的文件不存在竿刁、文件目錄不正確、訪問被拒絕搪缨、文件名輸入錯(cuò)誤食拜、省略了文件擴(kuò)展名“等錯(cuò)誤。
使用完文件后副编,必須使用close()方法將其關(guān)閉负甸。
可以結(jié)合使用ifstream變量和運(yùn)算符>>來讀取各種類型的數(shù)據(jù)。
可以結(jié)合使用ifstream變量和get()方法來讀取一個(gè)字符痹届,和getline()方法讀取一行字符串呻待。
結(jié)合使用ifstream變量和eof()、fail()等方法來判斷輸入是否成功队腐。
ifstream變量本身被用作測(cè)試條件時(shí)蚕捉,如果最后一個(gè)讀取操作成功,它將被轉(zhuǎn)換為布爾值true,否則被轉(zhuǎn)換為false香到。
雖然頭文件iostream提供了一個(gè)預(yù)先定義好的名為cin的istream對(duì)象鱼冀,但我們?cè)诓僮魑募r(shí)必須聲明自己的ifstream對(duì)象报破,并為其命名,將其同文件關(guān)聯(lián)起來千绪。此后便可以像使用cin那樣使用它充易。所有可用于cin的操作和方法都可用于它。
<pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="c++" cid="n62" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> ifstream fin;
fin.open("bowling.txt");
或者
char filename[50];
cin >> filename;
fin.open(filename);
if (!fin.is_open()) // if fail to open, then exit.
{
exit(EXIT_FALLURE); // must include "cstdlib",which contan "exit()".
}
char line[81];
fin.getline(line, 81); //read a line of text from fin
或者
double wt;
fin >> wt; //Get the first value from fin which is "bowling.txt"
while (fin.good())
{
...
fin >> wt; //Get the next value
}
或者
while (fin >> wt) //測(cè)試表達(dá)式的結(jié)果為fin,其再需要一個(gè)bool值的情況下荸型,
{ //fin的結(jié)果為fin.good(),即返回true或false.
...
}
if (fin.eof())
cout << "End of file reached.\n";
else if(fin.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";
fin.close();
return 0;</pre>
如果你的編譯器不支持is_open()方法盹靴,那么可以使用老的good()方法來替代它。但good()方法在檢查可能存在的問題方面沒有is_open()那么廣泛瑞妇。
- 方法eof()在遇到文件尾EOF時(shí)將返回true稿静;
- 方法fail()在遇到文件尾EOF或讀取的類型與左值不匹配時(shí)返回true;
- 方法bad()在遇到文件受損或硬件故障時(shí)返回True;
- 方法good()在沒有發(fā)生任何問題時(shí)返回true.
因此辕狰,由于good()在沒有任何問題時(shí)返回真改备,所以一般先使用good()判斷讀取成功否。因?yàn)閑of()只能判斷是否到達(dá)EOF蔓倍,而fail()可以檢查EOF和類型不匹配悬钳,因此如果good()返回假,那接著要判斷是否到達(dá)文件尾偶翅,這樣當(dāng)執(zhí)行到了fail()測(cè)試返回真默勾,便可斷定導(dǎo)致循環(huán)終止的原因是類型不匹配。同理聚谁,如果fail()返回假母剥,那就是其它原因?qū)е碌难h(huán)終止。
警告:Windows文本文件的每行都以回車加換行結(jié)尾形导;C++在讀取文件時(shí)自動(dòng)將這2個(gè)字符轉(zhuǎn)換為換行符环疼,并在寫入Windows文件時(shí)執(zhí)行相反的轉(zhuǎn)換。有些文本編輯器(Metrowerks Code Warrior IDE)骤宣,不會(huì)在最后一行末尾加上換行符秦爆。因此序愚,建議大家在輸完最后一行文本后憔披,按下回車鍵再保存關(guān)閉。