C++从Tab分隔文本读取12×10000数据至数组并实现列相乘
Hey there! Let's work through your problem step by step—you're close, but there are a few key issues in your code that are keeping you from storing the tab-separated data correctly. Let's break them down and fix things up.
First, Let's Identify the Key Bugs in Your Current Code
- Array Dimension Mix-Up: You declared
float array[12][10000], but this creates 12 rows and 10000 columns. Since your data is 10000 rows and 12 columns, you need to reverse it:float array[10000][12](rows first, columns second). - Incorrect Data Type for
line:getline()reads an entire line as astd::string, but you've declaredlineas afloat—this will cause a compilation error right away. - Trying to Assign a Whole Line Directly to an Array Row: You can't assign a string (or even a float) directly to an array row like
array[loop] = line—you need to split the tab-separated values in each line and convert them to floats one by one. while (!myfile.eof())is Unreliable: This loop condition often leads to reading the last line twice because the EOF flag isn't set until you try to read past the end of the file. A better approach is to tie your read operation directly to the loop condition.
Fixed Code (Using a Static Array)
Here's a corrected version that properly reads tab-separated values into your array:
#include <iostream> #include <fstream> #include <string> #include <sstream> // Needed for stringstream to split lines using namespace std; int main() { const int ROWS = 10000; const int COLS = 12; float array[ROWS][COLS] = {0}; // Initialize all values to 0 int currentRow = 0; // Track which row we're filling string line; // Store each full line as a string ifstream myfile("data.txt"); if (myfile.is_open()) { // Read each line directly in the loop condition while (getline(myfile, line) && currentRow < ROWS) { stringstream ss(line); // Convert the line into a stream we can read from float value; int currentCol = 0; // Split the line by tabs (>> automatically skips whitespace, including tabs) while (ss >> value && currentCol < COLS) { array[currentRow][currentCol] = value; currentCol++; } currentRow++; } myfile.close(); // Test: Print the first row to verify cout << "First row data: "; for (int col = 0; col < COLS; col++) { cout << array[0][col] << "\t"; } cout << endl; // Example: Multiply all columns in each row and print the result cout << "\nRow-wise column products:\n"; for (int row = 0; row < currentRow; row++) { float product = 1.0f; for (int col = 0; col < COLS; col++) { product *= array[row][col]; } cout << "Row " << row << ": " << product << endl; } } else { cout << "Unable to open file"; } system("PAUSE"); return 0; }
Key Improvements Explained:
stringstream: This lets us treat each line as a mini-input stream, so we can read individual float values from it (the>>operator automatically skips any whitespace, including tabs).- Loop Conditions: We check both that we successfully read a line and that we haven't exceeded the array's row limit (to avoid overflow).
- Initialization: The array is initialized to 0 to avoid garbage values if a line has fewer than 12 values.
- Column Multiplication Example: Added a simple loop that calculates the product of all columns for each row—you can adjust this to multiply specific columns (e.g., only columns 0 and 3) as needed.
Bonus: Using std::vector (More Flexible)
Since you mentioned you're not familiar with vector yet, here's a version using it—vectors are better because they automatically handle resizing (no need to hardcode 10000 rows) and are safer than static arrays:
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> // Include vector header using namespace std; int main() { const int COLS = 12; vector<vector<float>> data; // 2D vector: each element is a row of floats string line; ifstream myfile("data.txt"); if (myfile.is_open()) { while (getline(myfile, line)) { stringstream ss(line); vector<float> row; float value; int colCount = 0; while (ss >> value && colCount < COLS) { row.push_back(value); colCount++; } // Only add the row if it has all 12 columns (optional) if (row.size() == COLS) { data.push_back(row); } } myfile.close(); // Example: Multiply columns 0 and 1 for each row cout << "Product of column 0 and 1 for each row:\n"; for (size_t row = 0; row < data.size(); row++) { float product = data[row][0] * data[row][1]; cout << "Row " << row << ": " << product << endl; } } else { cout << "Unable to open file"; } system("PAUSE"); return 0; }
Why vector is Better:
- No need to hardcode the number of rows—
datawill grow as we add more rows. - You can easily get the number of rows with
data.size()and columns withdata[row].size(). - Less risk of overflow compared to static arrays (which have fixed sizes).
内容的提问来源于stack exchange,提问作者Jen Hansunn
相关产品推荐
相关产品推荐

