C++ 将文件读入矢量

C++ Read file into vectors

本文关键字:文件 C++      更新时间:2023-10-16

我在弄清楚如何将文件逐行读取到不同的数据类型向量中时遇到了麻烦。有没有办法用文件>>做到这一点?我的代码如下。提前感谢!

void fileOpen()
{
    fstream inFile;
    inFile.open(userFile);
    // Check if file open successful -- if so, process
    if (!inFile.is_open()) {cout << "File could not be opened.";}
    else
    {
        cout << "File is open.n";
        string firstLine;
        string line;
        vector<char> printMethod;
        vector<string> shirtColor;
        vector<string> orderID;
        vector<string> region;
        vector<int> charCount;
        vector<int> numMedium;
        vector<int> numLarge;
        vector<int> numXL;
        getline(inFile, firstLine); // get column headings out of the way
        cout << firstLine << endl << endl;
        while(inFile.good()) // while we are not at the end of the file, process
        {
            while(getline(inFile, line)) // get each line of the file separately
            {
               for (int i = 1; i < 50; i++)
               {
                  inFile >> date >> printMethod.at(i);
                  cout << date << printMethod.at(i) << endl;
               }
            }
        }
    }
}

在你的情况下使用vector.at(i)之前,你应该确保你的向量足够长,因为at会产生超出范围的异常。正如我从您的代码中看到的那样,您的矢量printMethod包含不超过 50 个元素,因此您可以在使用前调整矢量printMethod的大小,例如

vector<char> printMethod(50);

vector<char> printMethod;
printMethod.resize(50);

如果您打算使用超过 50 个的可变数量的元素,您应该使用push_back@Phil1970推荐的方法,例如

char other_data;
inFile >> date >> other_data;
printMethod.push_back(other_data);