C++读取文本文件并将每行存入不同Vector的技术求助
Solution for Reading CSV-like Lines into Vectors and LinkedList
Hey there! Let's break down how to solve your problem properly. Your current code only checks the file length with seekg, which isn't necessary for reading lines and splitting them—let's focus on the actual logic you need.
Key Steps to Implement:
- Read the file line by line: Use
getline()in a loop to fetch each line from the file automatically (no need to manually manipulate file pointers withseekghere). - Split each line by commas: Use a
stringstreamto parse each line and extract individual tokens separated by commas. - Store each line's tokens in a
vector: Create a newvectorfor every line, populate it with the split tokens. - Collect vectors into a
LinkedList: In C++, the standard linked list container isstd::list, so we'll usestd::list<std::vector<std::string>>to hold all our line vectors.
Complete Working Code:
#include <iostream> #include <fstream> #include <string> #include <vector> #include <sstream> #include <list> using namespace std; int main() { string fname; cout << "Please enter file name!" << endl; cin >> fname; fstream myfile(fname); if (!myfile.is_open()) { cout << "Unable to open your file!" << endl; return 1; } // LinkedList to hold all line vectors (using std::list) list<vector<string>> dataList; string line; // Read each line from the file while (getline(myfile, line)) { vector<string> lineTokens; stringstream ss(line); string token; // Split the line by commas while (getline(ss, token, ',')) { // Optional: Trim whitespace if your file has spaces after commas // (add code here if needed, e.g., remove leading/trailing spaces) lineTokens.push_back(token); } // Add the populated vector to the linked list dataList.push_back(lineTokens); } myfile.close(); // Example: Print out the data to verify cout << "Data stored in LinkedList of Vectors:" << endl; int lineNum = 1; for (const auto& vec : dataList) { cout << "Line " << lineNum++ << ": "; for (const auto& item : vec) { cout << item << " | "; } cout << endl; } return 0; }
Why seekg Didn't Help Here:
Your original use of seekg(0, ios_base::end) was just getting the total file size, which doesn't contribute to reading lines or splitting content. When using getline(), the file pointer is automatically advanced after each line is read, so manual pointer manipulation isn't required for this use case.
Notes for Your Next Steps:
- If your CSV lines have whitespace after commas (e.g.,
apple, banana, orange), you can add a helper function to trim whitespace from eachtokenbefore adding it to the vector. - You can now easily iterate over the
dataList(our linked list) to access each line's vector for further processing.
内容的提问来源于stack exchange,提问作者Vincent Lynn
相关产品推荐
相关产品推荐

