如何读取文件中的逗号分隔行并拆分为多种数据类型?
Parsing Comma-Separated Product Data in C++
Got it, let's fix up that Product::load method to properly parse your comma-separated product lines. First, let's recap the structure of each line you're dealing with:N,1234,box,kg,1,123.45,1,5
Which maps to these data types:
- Type:
char(e.g., 'N') - SKU:
int(e.g., 1234) - Name: C-style string (char array, e.g., "box")
- Unit: C-style string (char array, e.g., "kg")
- Taxed:
int/bool(e.g., 1 for true) - Price:
double(e.g., 123.45) - Quantity:
int(e.g., 1) - Qty Needed:
int(e.g., 5)
Here's the completed and robust version of your load method, with explanations:
#include <fstream> #include <cstring> #include <limits> // For std::numeric_limits // Assuming these constants are defined in your Product class/scope constexpr int max_sku_length = 10; // Adjust based on your needs constexpr int max_name_length = 50; constexpr int max_unit_length = 10; std::fstream& Product::load(std::fstream& file) { // Local variables to hold parsed values (match your class member names as needed) char type; int sku; char name[max_name_length + 1]; char unit[max_unit_length + 1]; int taxed_flag; // Using int since your example uses 1; switch to bool if preferred double price_; int quantity, qtyNeeded; char comma; // To capture the comma separators between fields // Read first field (type) and validate the following comma if (!(file >> type >> comma) || comma != ',') { file.setstate(std::ios::failbit); // Mark stream as failed if parsing breaks return file; } // Read SKU and comma if (!(file >> sku >> comma) || comma != ',') { file.setstate(std::ios::failbit); return file; } // Read product name (works if names have no spaces; use getline if spaces are possible) if (!(file >> name >> comma) || comma != ',') { file.setstate(std::ios::failbit); return file; } // Read unit and comma if (!(file >> unit >> comma) || comma != ',') { file.setstate(std::ios::failbit); return file; } // Read taxed flag and comma if (!(file >> taxed_flag >> comma) || comma != ',') { file.setstate(std::ios::failbit); return file; } // Read price and comma if (!(file >> price_ >> comma) || comma != ',') { file.setstate(std::ios::failbit); return file; } // Read quantity and comma if (!(file >> quantity >> comma) || comma != ',') { file.setstate(std::ios::failbit); return file; } // Read final field (qtyNeeded) if (!(file >> qtyNeeded)) { file.setstate(std::ios::failbit); return file; } // Assign parsed values to class members this->type = type; this->sku = sku; // SKU is numeric, so int is better than char array here std::strncpy(this->name, name, max_name_length); this->name[max_name_length] = '\0'; // Ensure null termination to avoid buffer issues std::strncpy(this->unit, unit, max_unit_length); this->unit[max_unit_length] = '\0'; this->taxed_ = static_cast<bool>(taxed_flag); // Convert to bool if your member uses that type this->price_ = price_; this->quantity = quantity; this->qtyNeeded = qtyNeeded; // Clean up remaining characters until end of line for next read file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); return file; }
Key Details to Note:
- Error Handling: Every read step checks if the operation succeeded and if the comma separator is present. If any step fails, we mark the stream as failed so the caller can handle errors (e.g.,
if (!product.load(file)) { /* log/handle bad line */ }). - Buffer Safety: When copying to class member char arrays, we use
strncpyand explicitly add a null terminator to prevent overflow. - End-of-Line Cleanup: The
ignorecall skips leftover characters (like trailing spaces or newlines) so the next read starts fresh on the next line. - Space-Friendly Names: If your product names might include spaces, replace
file >> namewithfile.getline(name, max_name_length + 1, ',')— just make sure to handle leading commas correctly in that scenario.
To use this method, you'd call it like this:
std::fstream productFile("products.csv", std::ios::in); Product product; while (product.load(productFile)) { // Process the loaded product (e.g., print, store in a list) }
内容的提问来源于stack exchange,提问作者Bot
相关产品推荐
相关产品推荐

