抱歉,我对c++有点陌生,但是我需要将txt文件中的数据组织到一个数组中(如果容易的话,也可以是 vector ),并且它需要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;
}
我期望结果是将数据组织成一个数组或 vector (我不知道如何使用 vector ),在其中可以乘以列,但由于无法正确将代码放入列中而导致错误。
最佳答案
这是一个适用于制表符或空格的简单解决方案。
#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。关于c++ - 您如何组织来自多维数组中文本文件的数据并从中乘以列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55427634/