C++如何将文本文件加载到二维vector中(命令行参数示例)
Great question! Let's walk through how to extend your existing code to read the file content into a 2D vector. I’ll assume your text file has whitespace-separated values (like numbers or strings) on each line—if your format is different, we can adjust, but this is the most common case.
Step 1: Complete Command Line Argument Check
First, finish validating that the user provided a filename. We need to check if argc is at least 2, since the first argument is always the program name itself.
Step 2: Open the File
Use std::ifstream to create a file object and open the target file. Always add a check to ensure the file opened successfully—this avoids silent failures if the file is missing or inaccessible.
Step 3: Read Lines and Populate the 2D Vector
For each line in the file:
- Read the entire line into a string.
- Use
std::istringstreamto split the line into individual elements. - Collect those elements into a 1D vector, then add that vector to your 2D container.
Here’s the complete, working code with these steps integrated:
#include <iostream> #include <vector> #include <fstream> #include <sstream> #include <string> using namespace std; int main(int argc, char* argv[]) { // 1. Validate command line arguments if (argc != 2) { cerr << "Usage: " << argv[0] << " <filename>" << endl; return 1; } // 2. Create file object and open the file ifstream inputFile(argv[1]); if (!inputFile.is_open()) { cerr << "Error: Could not open file " << argv[1] << endl; return 1; } // 3. Load content into 2D vector vector<vector<string>> twoDVector; // Switch to vector<vector<int>> for numeric data string line; while (getline(inputFile, line)) { vector<string> row; // Or vector<int> row; istringstream lineStream(line); string element; // Or int element; // Split line into elements (whitespace-separated) while (lineStream >> element) { // If using integers, convert here: row.push_back(stoi(element)); row.push_back(element); } // Add non-empty rows to the 2D vector (remove check to include empty rows) if (!row.empty()) { twoDVector.push_back(row); } } // Optional: Print the 2D vector to verify loading worked cout << "Loaded 2D vector content:" << endl; for (const auto& row : twoDVector) { for (const auto& elem : row) { cout << elem << " "; } cout << endl; } return 0; }
Key Notes:
- Data Type Flexibility: I used
vector<vector<string>>for general text. If your file contains integers, switch tovector<vector<int>>and convert each element withstoi(element)(usestolfor longs,stoffor floats, etc.). - Empty Lines: The code skips empty lines by checking if
rowis empty before adding it to the 2D vector—remove this check if you want to include empty rows. - Custom Delimiters: If your file uses commas or another delimiter instead of whitespace, replace
lineStream >> elementwithgetline(lineStream, element, ',')(swap','for your delimiter). - Error Handling: We added checks for missing arguments and failed file opening, which is critical for writing robust, user-friendly code.
内容的提问来源于stack exchange,提问作者cplusplusnewb

