gpt4 book ai didi

c++ - 如何使用 ifstream 从文件中读取行?

转载 作者:行者123 更新时间:2023-11-27 22:49:15 25 4
gpt4 key购买 nike

我有一个包含以下信息的文本文件:

    2B,410,AER,2965,KZN,2990,,0,CR2
2B,410,ASF,2966,KZN,2990,,0,CR2
2B,410,ASF,2966,MRV,2962,,0,CR2
2B,410,CEK,2968,KZN,2990,,0,CR2
2B,410,CEK,2968,OVB,4078,,0,CR2
2B,410,DME,4029,KZN,2990,,0,CR2
2B,410,DME,4029,NBC,6969,,0,CR2
2B,410,DME,4029,TGK,\N,,0,CR2

(是航线信息)

我正在尝试遍历文件并将每一行提取到一个 char* 中——简单吧?

嗯,是的,这很简单,但当您完全忘记如何编写成功的 i/o 操作时,情况就不那么简单了! :)

我的代码有点像:

char * FSXController::readLine(int offset, FileLookupFlag flag)
{
// Storage Buffer
char buffer[50];
std::streampos sPos(offset);

try
{
// Init stream
if (!m_ifs.is_open())
m_ifs.open(".\\Assets\\routes.txt", std::fstream::in);
}
catch (int errorCode)
{
showException(errorCode);
return nullptr;
}

// Set stream to read input line
m_ifs.getline(buffer, 50);

// Close stream if no multiple selection required
if (flag == FileLookupFlag::single)
m_ifs.close();

return buffer;

}

其中 m_ifs 是我的 ifStream 对象。

问题是当我在 getline() 操作后断点我的代码时,我注意到“缓冲区”没有改变?

我知道这很简单,但请有人对此有所了解 - 我正在撕掉我健忘的头发! :)

P.S:我从未完成异常处理的编写,所以它现在毫无用处!

谢谢

最佳答案

这里有一些您可能想学习的重要 C++ 库的修复程序,我认为这是一个更好的解决方案。因为你只需要你的最终结果是字符串:

// A program to read a file to a vector of strings 
// - Each line is a string element of a vector container
#include <fstream>
#include <string>
#include <vector>

// ..

std::vector<std::string> ReadTheWholeFile()
{
std::vector<std::string> MyVector;
std::string JustPlaceHolderString;
std::ifstream InFile;

InFile.open("YourText.txt"); // or the full path of a text file

if (InFile.is_open())
while (std::getline(InFile, PlaceHolderStr));
MyVector.push_back(PlaceHolderStr);

InFile.close(); // we usually finish what we start - but not needed
return MyVector;
}

int main()
{
// result
std::vector<std::string> MyResult = ReadTheWholeFile();

return 0;
}

关于c++ - 如何使用 ifstream 从文件中读取行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39212441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com