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

时间:2015-05-23 06:16:39

标签: c++

我已经吸取了教训,所以我会做短暂的,并且对于这个小学。

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

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

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;
}

1 个答案:

答案 0 :(得分:4)

我不确定你在问什么。

但是 - 下面是一些代码,它逐行读取文件并将行存储在向量中。代码还会打印行 - 包括文本行和每个字符的整数值。希望它有所帮助。

<invoiceReferenceNotificationMessage>

由于您的原始代码我不笑 - 没办法 - 我也曾经是初学者。但是你的代码是c风格的代码,包含很多bug。所以我的建议是:请改用c ++风格。例如:从不使用C风格的字符串(即char数组)。这很容易出错...

由于您是初学者(您自己的话:),请让我解释一下您的代码:

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;
}

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

正确的方法是:

char* title[1024];

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

这样的代码非常糟糕。如果输入文件有1025行怎么办?

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

std :: vector就像一个数组。但没有固定的大小。所以你可以继续添加它,它会自动调整大小。

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

祝你好运。

相关问题