0
相當簡單的問題。下面是我的代碼,我正在嘗試閱讀文本文件上每行的第一個單詞。我對C++非常陌生,基本上不識字,所以生動的解釋會非常有幫助。提前致謝!Getline在我的while循環中跳過第一行? (C++)
我想輸出是:
戰士(5次),狀態,巴特爾(5次),狀態(單獨當然行)
但我得到的是:
勇士(4次),狀態,巴特爾(5次),狀態
這裏是我的代碼:
int main() {
string readText;
string command;
string firstName;
string skip;
int strength;
ifstream inFile("warriors.txt");
if (!inFile) {
cout << "File will not open" << endl;
}
else {
while (inFile >> readText) {
getline(inFile, command);
inFile >> command;
if (command == "Warrior") {
cout << "warrior" << endl;
}
else if (command == "Battle") {
cout << "battle" << endl;
}
else if (command == "Status") {
cout << "status" << endl;
}
}
}
}
就在旁邊還有一個問題,那爲什麼當我改變:
while(inFile >> readText)
到
while(inFile)
我現在的輸出是: 勇士(4次),狀態,戰(5次),狀態,狀態
如果while循環內的條件非常有趣!怎麼樣cout << command << endl; – HazemGomaa
將while(inFile >> readText)改爲while(inFile >> command)並移除getline(inFile,command); inFile >>命令; – HazemGomaa
哦...那麼工作...謝謝!大聲笑 – Yourchingoo