#include <cstdlib> #include <iostream> #include <fstream> #include <string> #define FILE "studata.txt" using namespace std; typedef struct student //定义结构体,包括学号,姓名,性别,语文成绩,英语成绩,数学成绩,和指向下一个节点的指针 { int stunum; int chn_score; int eng_score; int math_score; char name[19]; char gender; struct student * next; }STU; /*int strToint(string s) { int i, num = 0; for(i = 0; i < s.size(); i++) num = num * 10 + s[i] - '0' ; return num; }*/ void showStudata(const STU * head) { const STU * ptr = head; cout.setf(ios::left); //设置对齐方式为left cout.width(8); cout << "学号"; cout.width(13); cout << "姓名"; cout.width(8); cout << "性别"; cout.width(10); cout << "语文成绩"; cout.width(10); cout << "英语成绩"; cout.width(10); cout << "数学成绩"; cout << '/n'; while(ptr) { cout.width(8); cout << ptr->stunum; cout.width(13); cout << ptr->name; cout.width(8); cout << ptr->gender; cout.width(10); cout << ptr->chn_score; cout.width(10); cout << ptr->eng_score; cout.width(10); cout << ptr->math_score; cout << '/n'; ptr=ptr->next; } } int main(int argc, char *argv[]) { string s; STU * first = NULL, * tail = NULL, * temp = NULL; ifstream ifs(FILE); if(!ifs) cout << "Open Error!" << '/n'; getline(ifs,s); //过滤第一行文字 if(ifs) { while(true) { temp = (STU *)malloc(sizeof(STU)); if(!temp) cout << "Error!" << '/n'; else{ ifs >> s; temp -> stunum = atoi(s.c_str()); //有读入数据的话,ifs返回一个地址值 ifs >> s; strcpy(temp->name, s.c_str()); ifs >> s; temp->gender = *s.c_str(); ifs >> s; temp -> chn_score = atoi(s.c_str()); ifs >> s; temp -> eng_score = atoi(s.c_str()); ifs >> s; temp -> math_score = atoi(s.c_str()); if(!ifs) //最后没有读入数据了,ifs = 0 { tail -> next = NULL; delete temp; break; } if(first == NULL) first = tail= temp; else { tail -> next = temp; tail = temp; } } } } if(first != NULL) tail -> next = NULL; showStudata(first); system("PAUSE"); return EXIT_SUCCESS; }