如何仅用fstream读取包含char、short、float类型数值的CSV文件?
Alright, let's break this down for you. You want to parse a CSV with fixed-order char, short, float values (comma-separated, multi-line) using only the <fstream> header—no stringstream, temp char arrays, or external libraries. Totally doable, here's a straightforward approach:
Solution Using Only
<fstream> First, let's define a simple struct to hold each row's data (this keeps things organized instead of juggling separate arrays):
#include <fstream> #include <vector> // Match this struct to your fixed column order! // Example order: char → float → float → short (matches your sample input) struct CSVRow { char id; float val1; float val2; short count; }; int main() { // Open the CSV file std::ifstream csv_file("your_data.csv"); if (!csv_file.is_open()) { // Handle file open failure (e.g., print an error message) return 1; } std::vector<CSVRow> dataset; // Store all rows here (use a raw array if you prefer) CSVRow current_row; char comma; // Dummy variable to consume the commas between values // The magic loop: read values and skip commas automatically while (csv_file >> current_row.id >> comma >> current_row.val1 >> comma >> current_row.val2 >> comma >> current_row.count) { dataset.push_back(current_row); } // Optional: Verify the data was read correctly for (const auto& row : dataset) { // Cast char to int to print its numeric value instead of the ASCII character std::cout << static_cast<int>(row.id) << ", " << row.val1 << ", " << row.val2 << ", " << row.count << "\n"; } csv_file.close(); return 0; }
How This Works (No Tricky Stuff!)
- No
stringstreamrequired: We usestd::ifstream's built-in extraction operator (>>), which automatically skips whitespace (including newlines between rows) so we don't have to handle line breaks manually. - Comma handling: The dummy
char commavariable reads and discards the commas separating values. This keeps the extraction sequence perfectly aligned with your CSV structure. - Flexible storage:
std::vector<CSVRow>lets you handle any number of rows without pre-defining an array size. If you must use a raw array, you can first count the rows (loop through the file withgetlineto count newlines) then allocate the array accordingly.
Key Notes
- Double-check that your CSV follows the fixed column order exactly—missing values or extra commas will cause the read loop to terminate early.
- If your column type order is different (e.g.,
shortfirst, thenchar, thenfloat), just reorder the members inCSVRowand adjust the extraction order in thewhileloop. - Whitespace around commas (like
1 , 2.3) is totally fine—the>>operator ignores leading whitespace automatically.
内容的提问来源于stack exchange,提问作者a concerned citizen
相关产品推荐
相关产品推荐

