[問題] 輸入姓名跑出成績

看板C_and_CPP作者 (楓的旋律)時間15年前 (2010/05/21 12:35), 編輯推噓3(3010)
留言13則, 5人參與, 最新討論串1/1
#include <fstream> //載入fstream標頭檔 #include <iostream> //載入iostream標頭檔 #include <cstdlib> //載入cstdlib標頭檔 #include <string> #define SIZE 200 using namespace std; int binarySearch(string x[], int n, string key) { bool found = false; int index, head = 0, tail = n, mid; while(!found && (tail >= head)) { mid = (head + tail) / 2; if(key == x[mid]) { found = true; index = mid; break; } else if(key > x[mid]) head = mid + 1; else tail = mid - 1; } return (found? index:-1); } void show_data( string name[], int grade[], int n ) { for( int i = 0; i < n; i++ ) cout << name[i] << "\t" << grade[i] << endl; } void myMenu() //設定選單的函數 { cout << "\n\n===== 選 單 =====" << endl; cout << "0. 結束" << endl; cout << "1. 顯示資料內容" << endl; cout << "2. 以姓名查詢成績" << endl; cout << "請選擇(1~3, 0 = 結束): "; } int main() //主程式 { string name[SIZE], key; int grade[SIZE], n; int choice, result; //定義整數 choice ifstream ifile("c:\\grade.txt", ios::in ); //開啟grade.txt檔案 if( ifile == NULL ) { cout << "Error: cannot open file!" << endl; system( "pause" ); exit( 1 ); } n = 0; while( !ifile.eof() ) { ifile >> name[n] >> grade[n]; n++; } ifile.close(); do { myMenu(); //呼叫選單的函數 cin >> choice; //輸入要做的CASE switch( choice ) { case 1: cout << "1. 顯示資料內容" << endl; show_data( name, grade, n ); // break; //跳離switch敘述 case 2: cout << "2. 以姓名查詢成績" << endl; cout << "請輸入要查詢的姓名" << endl; cin>>key; //輸入要查詢的數字 result = binarySearch( name, n, key); if(result == -1) cout << "你所要查詢的資料不在資料庫裡!!!" << endl; else cout << key<< "的分數是"<< grade[result] << endl ; break; //跳離switch敘述 } } while( choice != 0 ); //選擇0時離開程式 system( "pause" ); return 0; } 這是我目前的程式 有一個檔案 grade.txt 放在C 內容是 John 85 Tom 90 May 89 Apple 91 Bob 81 Jack 55 Jenny 96 Aby 77 Dan 89 我現在的問題在case 2 要怎麼輸入姓名讓他跑出成績呢?? 因為這個檔案沒有照字母排列 所以無法順利跑出 所以我是要先寫一個讓他排列的方法嗎?? 還是有其他方法可以直接比較輸入的key 跟name[]字串??? 請高手教教我~~謝謝!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.46.215.118

05/21 12:41, , 1F
binarysearch 必須先排列 看你是要用 qsort 還是自己寫都可
05/21 12:41, 1F

05/21 14:39, , 2F
這就是我不會的地方= =該怎麼弄呢??
05/21 14:39, 2F

05/21 14:41, , 3F
因為 string 類的陣列了,直接套sort或stable_sort就行
05/21 14:41, 3F

05/21 14:42, , 4F
非排列後用binarysearch不可嗎?? 直接對每個名字做
05/21 14:42, 4F

05/21 14:42, , 5F
linear search也可以做到吧?? C++的話, 是不是有某個更
05/21 14:42, 5F

05/21 14:43, , 6F
方便簡單的STL可以用啊@_@"
05/21 14:43, 6F

05/21 14:46, , 7F
binarysearch 假設資料可以切成三個區段, 不排序先決
05/21 14:46, 7F

05/21 14:46, , 8F
條件就不成立了
05/21 14:46, 8F

05/22 06:53, , 9F
是老師規定一定要binary search嗎? 還是你找到的程式碼
05/22 06:53, 9F

05/22 06:54, , 10F
不然linear search會比較簡單阿XDDinput size應該不大
05/22 06:54, 10F

05/22 06:55, , 11F
如果想學會做 quick sort 排序, 可以看以下檔案
05/22 06:55, 11F

05/22 06:56, , 12F

05/22 06:58, , 13F
仔細看, 裡面有教字串 sort 唷 A_A
05/22 06:58, 13F
文章代碼(AID): #1BzWs6Dd (C_and_CPP)