c++ - 如何在多维数组中组织文本文件中的数据并从中乘以列?
问题描述
抱歉,我对 c++ 有点陌生,但我需要将 txt 文件中的数据组织成一个数组(或向量,如果这更容易的话),它需要有 12 列和 10000 行。我需要能够将这些列相乘,但我无法将数据放入行中。数据由制表符解析,并且已经是 12x10000 格式。我怎样才能只使用 c++ 做到这一点?
我已经尝试在网上查找,除了阅读文本外,我什么也没有。我还有 225 行代码,这些都是我尝试过的所有尝试。它基本上归结为这些线。我有一个解析器,但它除了按制表符划分数据之外什么都不做,而不是识别它。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
float array[12][10000]; // creates array to hold names
long loop=0; //short for loop for input
float line; //this will contain the data read from the file
ifstream myfile ("data.txt"); //opening the file.
if (myfile.is_open()) //if the file is open
{
while (! myfile.eof() ) //while the end of file is NOT reached
{
getline (myfile,line); //get one line from the file
array[loop] = line;
cout << array[loop] << endl; //and output it
loop++;
}
myfile.close(); //closing the file
}
else cout << "Unable to open file"; //if the file is not open output
system("PAUSE");
return 0;
}
我希望结果是组织成数组或向量的数据(我不知道如何使用向量),我可以在其中乘以列,但它只是因为我无法正确地将代码放入列中而出现错误。
解决方案
这是一个简单的解决方案,适用于制表符或空格的分隔符。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
constexpr size_t rows_len = 10000;
constexpr size_t cols_len = 12;
int main ()
{
float array[rows_len][cols_len]{}; // value initialization to ensure unfilled cells at 0
ifstream myfile("data.txt");
if (!myfile.is_open()) {
cout << "Unable to open file" << endl;
return 1;
}
string line;
for (size_t row = 0; row < rows_len && myfile; row++) {
getline(myfile, line);
const char* s = line.c_str();
for (size_t col = 0; col < cols_len; col++) {
char* p = nullptr;
array[row][col] = strtof(s, &p);
s = p;
}
}
// use array ...
return 0;
}
的第二个参数strtof()
允许知道下一个单元格的开始在哪里。如果单元格不是数字,则所有剩余的行都array
设置为 0。