【討論】電腦16-2


Recommended Posts

ifstream fin("路徑")是連結並開啟和ofstream相同

if(!fin)和if(!fout)意思相同

fin的用法和cin相同

fin.close()切斷連結

fin.eof():

到達檔案的終點(最後一行)時傳回true(1);其餘傳回false(0)

重點

cout:c++到螢幕

cin:鍵盤到螢幕

fout:c++到檔案

fin:檔案到c++

補充string vs. char[ ]


[B]操作[/B] [B]string 字元陣列[/B]
宣告字串 string s; char s[100];
取得第 i 個字元 s[i] s[i]
字串長度 s.length()
或 s.size() strlen(s)
讀取一行 getline(cin, s); gets(s);
設成某字串 s="ck130"; strcpy(s, "ck130");
字串相加 s=s+"ck130"; strcat(s, "ck130");
字串比較 s=="ck130" strcmp(s, "ck130")

個人覺得string比較人性化


#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
ifstream fin("score.txt");
if(!fin){
cout<<"檔案無法開啟\n";
system("pause");
return 0;
}
string score;
int i=0;
while(1){
getline(fin,score);
if(fin.eof())break;
else if(!i)
cout<<"學生人數:"<<score<<"人\n";
else
cout<<i<<"號學生成績:"<<score<<"分\n";
i++;
}
fin.close();
system("pause");
}

鏈接文章
分享到其他網站