且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从文件中读取多行字符串并将其存储在C ++中的字符串数组中

更新时间:2023-02-24 12:38:19

NumberOfStrings++ is outside of your for loop when you read (i.e. it only gets incremented once). Also please consider using std::vector<std::string> instead of a dynamic array.

Here's a version of your code using std::vector instead of an array:

#include <vector>
#include <fstream>
#include <iostream>
#include <string>

class StringList
{
public:
    StringList(): str(1000000), numberOfStrings(0)
    {
        std::ifstream myfile ("Read.txt");
        if (myfile.is_open())
        {
            for (int i = 0; i < str.size(); i++)
            {
                getline(myfile, str[i]);
                numberOfStrings++;
            }

            myfile.close();
        }
    }

    StringList::~StringList()
    {
        std::ofstream os("Read.txt");
        for (int i = 0; i <numberOfStrings; i++) 
        {
            os << str[i] << std::endl;
        }
    }

private:
    std::vector<std::string> str;
    int numberOfStrings;
};

As you can see the changes are rather minimal.

相关阅读

技术问答最新文章