C++.从文本文件读取.每隔一段就缺失一次
C++. Reading from text file. Every second segment is missing
我在文本文件中有以下数据:
...
A,Q1,1
S,a1,a1
S,a2,a2
S,a3,a3
A,Q1,1
S,b1,b1
S,b2,b2
S,b3,b3
A,Q1,1
S,c1,c1
S,c2,c2
S,c3,c3
A,Q1,1
S,d1,d1
S,d2,d2
S,d3,d3
A,Q2,1
S,x1,x1
S,x2,x2
S,x3,x3
...
我使用以下代码提取数据:
std::string MyClass::getData(const std::string& icao)
{
// Final String
std::string finalData = "";
// Path to the Navigraph Navdata
std::string path = getPath();
std::string dataFilePathSmall = navdataFilePath + "ats.txt";
// Create file streams
std::ifstream ifsSmall(dataFilePathSmall.c_str());
// Check if neither of the files exists.
if (!ifsSmall.is_open())
{
// If it does not exist, return Not Available
finalData = "FILE NOT FOUND";
}
// If the file 'ats.txt' exists, pull the data relevant to the passed ICAO code
if (ifsSmall)
{
// We need to look a line starting with the airway prefixed by "A," and suffixed by ','
const std::string search_string = "A," + icao + ',';
// Read and discard lines from the stream till we get to a line starting with the search_string
std::string line;
// While reading the whole documents
while (getline(ifsSmall, line))
{
// If the key has been found...
if (line.find(search_string) == 0)
{
// Add this line to the buffer
finalData += line + 'n';
// ...keep reading line by line till the line is prefixed with "S"
while (getline(ifsSmall, line) && (line.find("S,") == 0))
{
finalData += line + 'n'; // append this line to the result
}
}
}
// If no lines have been found
if (finalData == "")
{
finalData = "CODE NOT FOUND";
}
}
// Close the streams if they are open
if (ifsSmall)
{
ifsSmall.close();
}
return finalData;
}
现在,我的问题是,由于某种原因,每隔一段数据都没有被读取。也就是说,我收到以下内容:
A,Q1,1
S,a1,a1
S,a2,a2
S,a3,a3
A,Q1,1
S,c1,c1
S,c2,c2
S,c3,c3
我无法弄清楚我的代码中到底缺少什么。提前非常感谢!
while (getline(ifsSmall, line) && (line.find("S,") == 0))
将读取一行并检查它是否以"S"开头。如果它不是以"S"开头,则该行仍已读取。对于您的while+if读取以"A"开头的行也是如此。
内部循环读取不以"S"开头的行,然后终止。这是您缺少的以"A"开头的行。然后,外部循环读取另一行,因此它错过了节的开头。
尝试只使用一个循环和一个 getline((。
相关文章:
- 在做一段时间内检查字符的无限循环
- 如何为一段代码启用 -permissive
- ExtTextOut 文本的持续闪烁,在一段时间后,文本将恢复为默认字体
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- 使用Qt Creator在调试模式下编译一段代码
- ::grpc::ServerReaderWriter 对象在另一个线程中一段时间后无法调用
- 一段时间后 CPU 使用率高
- 有没有办法在一段时间后将流程从流出中分离出来
- 无法理解一段具有完美转发和省略号的C++代码
- 在一段时间内更改标签文本
- 布尔函数在一段时间内不起作用
- 防止一段代码在协程中并发执行
- 埃拉托色尼的筛子在一段上
- 解决PNP在一段时间后返回坏的rvec和tvec
- 相机的旋转方向在一段时间后反转
- C++.从文本文件读取.每隔一段就缺失一次
- 动态字符字段一次读取一个字符
- 从第二次调用开始在函数中执行一段代码
- 如何只执行一段代码一次
- 用arduino/c++在一段时间内短时间闪烁LED 1到3次