繁体   English   中英

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

[英]How to read lines from a file using the ifstream?

我有一个文本文件,其中包含以下信息:

    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()操作之后对代码进行断点处理时,我注意到“ buffer”没有改变吗?

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

PS:我从来没有写完异常处理,所以现在它非常没用!

谢谢

这是一些您可能想学习的重要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;
}

您的代码有两个基本问题:

  1. 您正在返回一个局部变量。 语句return buffer; 导致指针dangling

  2. 您正在使用char buffer 不鼓励在C ++中使用C风格的字符串,您应始终首选std::string

更好的方法是:

string FSXController::readLine(int offset, FileLookupFlag flag) {
    string line;
    //your code here 

    getline(m_ifs, line) //or while(getline(my_ifs, line)){ //code here } to read multiple lines
    //rest of your code
    return line;
}

关于std::string更多信息可以在这里找到

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM