Re: [問題] 判斷輸入exit就停止

看板C_and_CPP作者 (高髮箍)時間14年前 (2011/11/26 01:11), 編輯推噓3(304)
留言7則, 4人參與, 最新討論串2/2 (看更多)
※ 引述《heeyahan (阿草)》之銘言: : 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) : VB2008 : 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) : 問題(Question): : 要怎麼讓使用者可以一直輸入資料 直到輸入exit就停止 : 餵入的資料(Input): : 預期的正確結果(Expected Output): : 錯誤結果(Wrong Output): : 程式碼(Code):(請善用置底文網頁, 記得排版) : http://codepad.org/VSeJ4WBu : http://codepad.org/siltm7lw : 補充說明(Supplement): : 我有去google這個問題 也知道可以用strcmp這個函式去做 : 但是用這個函式的時候 變數好像都要是char才有辦法比較 : 如果我的變數都是int 那該怎麼做? 一直輸入整數的程式長這樣: int input; while( cin >> input ) cout << input << endl; 直到使用者輸入 exit 才結束, 那就用字串來暫存: char input[ 12 ]; while( cin >> input && strcmp(input,"exit") ) cout << input << endl; 為了和你的資料結構做銜接, 再從字串轉回來即可: #include <cstdlib> while( cin >> input && strcmp(input,"exit") ) { char *end; int value = (int)strtol( input, &end, 10 ); if( end == input + strlen(input) ) { // 轉型成功 → 放進 heap 裡 } else { // 轉型失敗 → 結束迴圈 } } IO的部份確認沒問題時, 才繼續往下寫, 像 min/max heap 這種常 用的結構有內建函式幫你建就不要自己再造一個: typedef vector<int> Heap; Heap heap; heap.reserve( 128 ); // 預留 128 個元素的空間 heap.push_back( 7 ); // 加入新元素 heap.push_back( 9 ); heap.push_back( 2 ); // 印出建置前的內容 copy( heap.begin(), heap.end(), ostream_iterator<Heap::value_type>(cout, " ") ); cout << endl; greater<Heap::value_type> comparator; // 建置符合 min-heap 的結構 make_heap( heap.begin(), heap.end(), comparator ); // 印出建置後的內容 copy( heap.begin(), heap.end(), ostream_iterator<Heap::value_type>(cout, " ") ); cout << endl; // 最小值 cout << heap.front() << endl; // 拿出最小值 pop_heap( heap.begin(), heap.end(), comparator ); // 去掉最小值 heap.pop_back(); // 印出第二小值 cout << heap.front() << endl; 使用標準函式庫不是不認同你的實作, 因為標準即共通語言, 這在 考驗你跟其他程式設計師的溝通能力. -- ★ ★ ███ ███ █▌█ ██◣ ███ ▋▋█ █▂█ █▃█ ███ █▆█ █▄█ ███ █ ◣ █ █ ▋██ █▆◤ ███ ███ Kim Jae Kyung Koh Woo Ri Cho Hyun Young Kim Ji Sook φwindyhorse No Eul Oh Seung A Jung Yoon Hye -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.121.197.115

11/26 01:30, , 1F
跟版本的意見一樣,多一層方法去接受使用者認為的數字或
11/26 01:30, 1F

11/26 01:30, , 2F
11/26 01:30, 2F

11/26 01:30, , 3F
字串指令, 再分別處理.
11/26 01:30, 3F

11/26 02:20, , 4F
我真是太配服版主了,思緒架構很清晰。
11/26 02:20, 4F

11/26 12:41, , 5F
快拜<(m.m)>
11/26 12:41, 5F

11/27 13:44, , 6F
推板主
11/27 13:44, 6F

11/28 10:30, , 7F
超哥出現了
11/28 10:30, 7F
文章代碼(AID): #1Epyn6-6 (C_and_CPP)
文章代碼(AID): #1Epyn6-6 (C_and_CPP)