[英]Why is getline not moving to next line?
所以我不知道為什么我的getline循環在處理完第一行后不會移到下一行。 這段代碼的目的是獲取一個看起來像這樣的文本文件:
a 22.55736 110.9237 10.0 9.0 8.0 -1.0 1.0 -1.0 5.0 6.0 11.0
b 40.5567 50.556 10.0 9.0 8.0 -1.0 1.0 -1.0 5.0 6.0 11.0
c 26.7798223 24.5 10.0 9.0 8.0 -1.0 1.0 -1.0 5.0 6.0 11.0
逐行閱讀各行,將元素(由空格分隔)復制到各個變量中,以備將來使用。 為了檢查標記化,我逐行將變量輸出到output.txt文件中,以確保代碼正常工作。 這是代碼:
#include "stdafx.h""
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main() {
string stringLine;
ifstream inFile;
inFile.open("missionData.txt");
ofstream outputFile;
outputFile.open("outputFile.txt");
if (inFile.good())
{
while (getline(inFile, stringLine))
{
//getline(inFile, stringLine); //Read line from txt into stringLine
istringstream iss(stringLine);
vector<string> lineArray{ istream_iterator<string>{iss},
istream_iterator<string>{} };
//Convert tokenized vector into individual, usable parameters
const char* funcType = lineArray.at(0).c_str();
double lat = atof(lineArray.at(1).c_str());
double lon = atof(lineArray.at(2).c_str());
float alt = stof(lineArray.at(3));
float speed = stof(lineArray.at(4));
float radius = stof(lineArray.at(5));
float yaw = stof(lineArray.at(6));
float duration = stof(lineArray.at(7));
float imgOn = stof(lineArray.at(8));
float vidOn = stof(lineArray.at(9));
float micOn = stof(lineArray.at(10));
float sensOn = stof(lineArray.at(11));
int i = 0;
while (i < 12)
{
outputFile << funcType << endl;
outputFile << lat << endl;
outputFile << lon << endl;
outputFile << alt << endl;
outputFile << speed << endl;
outputFile << radius << endl;
outputFile << yaw << endl;
outputFile << duration << endl;
outputFile << imgOn << endl;
outputFile << vidOn << endl;
outputFile << micOn << endl;
outputFile << sensOn << endl;
}
}
inFile.close();
}
return 0;
}
理想情況下,輸出文件將顯示輸入文件的3行中的每個元素,每行顯示一個元素,一旦.good返回false(到達eof)就停止。 事實證明,我很好地分離了元素,但是查看輸出文件會發現第一行重復出現,每行重復一個元素(應該是這樣)。 就像getline停留在輸入文件的第一行一樣,無法前進。 知道發生了什么嗎? 謝謝!
int i = 0;
while (i < 12)
{
outputFile << funcType << endl;
outputFile << lat << endl;
// ...
}
這是一個無限循環,因為您永遠不會更改i
的值。 因此, getline
永遠不會讀取第二行,因為getline
不會被第二次調用-在此之前,代碼陷入了無限循環。
PS:即使您將其固定為迭代12次(如您預期的那樣),我仍然想知道打印十二次相同信息的目的是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.