逐行读取文件,并将值存储到数组/字符串中

Read file, line by line, and store values into a array/string?

本文关键字:数组 字符串 存储 文件 读取 逐行      更新时间:2023-10-16

我已经得到了教训,所以我将长话短说。

我需要一个函数,在我的类中,可以逐行读取文件,并将它们存储到数组/字符串中,以便我可以使用它。

我有下面的例子(请不要笑,我是一个乞丐):

int CMYCLASS::LoadLines(std::string Filename)
{
    std::ifstream input(Filename, std::ios::binary | ios::in);
    input.seekg(0, ios::end);
    char* title[1024];
    input.read((char*)title, sizeof(int)); 
    // here what ?? -_-
    input.close();

    for (int i = 0; i < sizeof(title); i++)
    {
            printf(" %.2X ";, title[i]); 
    }
    printf("");
    return 0;
}

我不太清楚你到底在问什么。

然而,下面是一些逐行读取文件并将行存储在vector中的代码。该代码还打印行——既作为文本行,也作为每个字符的整数值。希望能有所帮助。

int main()
{
    std::string Filename = "somefile.bin";
    std::ifstream input(Filename, std::ios::binary | ios::in);  // Open the file
    std::string line;                                           // Temp variable
    std::vector<std::string> lines;                             // Vector for holding all lines in the file
    while (std::getline(input, line))                           // Read lines as long as the file is
    {
       lines.push_back(line);                                   // Save the line in the vector
    }
    // Now the vector holds all lines from the file
    // and you can do what ever you want it
    // For instance we can print the lines
    // Both as a line and as the hexadecimal value of every character
    for(auto s : lines)                                         // For each line in vector
    {
        cout << s;                                              // Print it
        for(auto c : s)                                         // For each character in the line
        {
            cout << hex                                         // switch to hexadecimal
                 << std::setw(2)                                // print it in two 
                 << std::setfill('0')                           // leading zero
                 << (unsigned int)c                             // cast to get the integer value
                 << dec                                         // back to decimal
                 << " ";                                        // and a space
        }
        cout << endl;                                           // new line
    }
    return 0;
}

我不笑由于你的原始代码-不可能-我也是一个初学者曾经。但是你的代码是c风格的代码,包含很多bug。所以我的建议是:请使用c++风格。例如:永远不要使用c风格的字符串(即char数组)。这是如此容易出错…

由于你是一个初学者(你自己的话:),让我来解释一些关于你的代码的事情:

char* title[1024];

这不是字符串。它有1024个指向字符的指针,也可以有1024个指向c风格字符串的指针。但是,您没有为保存字符串保留任何内存。

正确的方法是:

char title[1024][256];  // 1024 lines with a maximum of 256 chars per line

这里你必须确保输入文件少于1024行,每行少于256个字符。

像那样的代码是非常糟糕的。如果输入文件有1025行,该怎么办?

这就是c++可以帮助你的地方。使用std::string,您不需要担心字符串的长度。std::string容器会根据你输入的大小进行调整。

std::vector类似于数组。但是没有固定的尺寸。所以你可以继续添加它它会自动调整大小。

所以c++提供了std::string和std::vector来帮助你处理输入文件的动态大小。使用它…

好运。