[問題] getline抓到錯誤的字?

看板C_and_CPP (C/C++)作者 (腦殘並不可恥)時間14年前 (2012/05/06 15:52), 編輯推噓0(004)
留言4則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux g++ 問題(Question): while ( !inFile.eof() ) { getline (inFile, cmd, ' '); if (cmd == "insert"){ getline (inFile, name, ' '); cout << '>' << name << '<' << endl; getline (inFile, temp, ' '); int x = atoi(temp.c_str()); getline (inFile, temp, ' '); int y = atoi(temp.c_str()); getline (inFile, temp, ' '); int w = atoi(temp.c_str()); getline (inFile, temp); int h = atoi(temp.c_str()); cout << cmd << ' ' << name << ' ' << x << y << ' ' << w << h << ' '; list->Insert(name, x, y, w, h); } else if (cmd == "search"){ cout << '>' << name << '<' << endl; getline (inFile, name); cout << cmd << endl; cout << '>' << name << '<' << endl; if (list->Search(name) == 0) cout << "...not found" << endl; else cout << "...found" << endl; } } 餵入的資料(Input): insert rect1 10 70 45 10 insert rect2 25 50 10 50 search rect2 search rect1 預期的正確結果(Expected Output): >rect1< insert rect1 1070 4510 >rect2< insert rect2 2550 1050 >rect2< search >rect2< ...found >rect2< search >rect1< ...found 錯誤結果(Wrong Output): >rect1< insert rect1 1070 4510 >rect2< insert rect2 2550 1050 >rect2< search <rect2 ...not found <rect2 search <rect1 ...not found 我在用getline讀search這行時,第二個參數讀進來後印出來竟然是<rect2。 原本應該是要>rect2<才對,這連帶使我用錯誤的name去search我的list, 結果當然就是找不到,有人知道為什麼嗎? getline (inFile, name)不是應該會讀到換行為止嗎? 之前insert讀到的第二個參數都是正確的,為何一樣的寫法會讀到錯誤的字? 感謝程式高手解答,謝謝!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 199.74.99.54

05/06 16:32, , 1F
看來應該是 '\r' 的問題
05/06 16:32, 1F

05/06 16:46, , 2F
不過你怎麼還沒讀就先印了?
05/06 16:46, 2F

05/06 17:25, , 3F

05/06 23:36, , 4F
可以了耶 loveme你實在太強了 我根本不知道可以這樣寫 謝謝
05/06 23:36, 4F
文章代碼(AID): #1FfYseQQ (C_and_CPP)
文章代碼(AID): #1FfYseQQ (C_and_CPP)