[問題] getline抓到錯誤的字?
開發平台(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
05/06 16:32, 1F
→
05/06 16:46, , 2F
05/06 16:46, 2F
→
05/06 17:25, , 3F
05/06 17:25, 3F
→
05/06 23:36, , 4F
05/06 23:36, 4F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章