C++期末成績存放在文本檔案 “Score.txt”中,要求撰寫程式讀取該文本檔案創建鏈表,并在鏈表上根據學號查找姓名和成績。
??文本檔案的各列之間使用空格分隔,檔案行數不確定。??要求使用ifstream類和ofstream類的物件讀取和寫入資料。??鏈表的一個結點可宣告如下:struct student { unsigned long id; string name; float score; student *next; //下一個結點的指標}
??回圈從鍵盤讀入學號,查詢對應的姓名和成績,輸入學號為0時退出回圈。




uj5u.com熱心網友回復:
就是一行一行讀,每一行讀三個欄位uj5u.com熱心網友回復:
大哥有空幫寫下這個程式么,可以有償,沒時間再從鏈表開始學了,感謝
uj5u.com熱心網友回復:
給你寫個sample吧#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <string>
typedef struct student {
unsigned long id;
string name;
float score;
student *next;
} STU;
STU* loadScore(const char *filename) {//加載檔案資訊
int cnt=0, idx=0;
string line, item;
STU *head, *stu=NULL;
ifstream in("/Users/qinyb/Score.txt");
stu = head = new STU;
while (getline(in, line, '\n'))
{
if (line.empty())
continue; //空行不做處理
if (cnt>0) {
stu->next = new STU;
stu = stu->next;
}
stringstream ss(line);
idx = 0;
while(getline(ss, item, ' ')) //按空格分割
{
if(!item.empty()) {
if(idx==0)
stu->id = stol(item);
else if(idx==1)
stu->name = item;
else if (idx==2)
stu->score = stof(item);
idx++;
}
}
cnt++;
}
stu->next = NULL;
in.close();
return head;
}
void printScore(STU* list) {//列印鏈表
STU *p = list;
int cnt = 0;
while (p!=NULL) {
cnt++;
printf("第%d個學生:學號[%ld], 姓名[%s], 成績[%.2f]\n", cnt, p->id, p->name.c_str(), p->score);
p = p->next;
}
}
void releaseScore(STU* list) {//釋放鏈表
STU *p = list;
while (p!=NULL) {
STU *q = p;
p = p->next;
delete q;
}
}
STU* searchStudent(STU* list, unsigned long id) { //檢索學號
STU *p = list;
while (p!=NULL) {
if (p->id == id) {
break;
}
p = p->next;
}
return p;
}
int main ()
{
STU *list = loadScore("Score.txt");
printScore(list);
unsigned long id = 0;
while(1) {//模擬學生查詢
cout<<"請輸入查詢學生的學號:";
cin>>id;
if (id==0) {
cout<<"退出學生查詢系統..."<<endl;
break;
}
STU *stu = searchStudent(list, id);
if (stu==NULL) {
cout<<"查找不到資訊!"<<endl;
} else {
printf("查找到資訊:學號[%ld], 姓名[%s], 成績[%.2f]\n", stu->id, stu->name.c_str(), stu->score);
}
}
releaseScore(list);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/59052.html
標籤:C++ 語言
