在 C++ 中,我想读取一个包含 float 列的文本文件并将它们放入二维数组中。
第一行将是第一列,依此类推。
数组的大小是未知的,它取决于可能变化的行和列。
我尝试过使用“getline”、“inFile >>”,但我所做的所有更改都有一些问题。
例如,有没有办法在值存在后删除不需要的行/行?
文件看起来像这样(+/-):
- 字符“\t”字符“\t”字符“\n”
- float “\t” float “\t” float “\t” float “\n”
- float “\t” float “\t” float “\t” float “\n”
- float “\t” float “\t” float “\t” float “\n”
谢谢
到目前为止我有这个:
int ReadFromFile(){
ifstream inFile;
ofstream outFile;
int nLinActual = 0;
const int nCol = 9;
const int nLin = 10;
// open file for reading
inFile.open("values.txt");
// checks if file opened
if(inFile.fail()) {
cout << "error loading .txt file reading" << endl;
return 1;
}
// open file for writing
outFile.open ("outArray.txt");
// checks if file opened
if(outFile.fail()) {
cout << "error loading .txt file for writing" << endl;
return 1;
}
// Doesn't read the first line
string dummyLine, dummyLine2, dummyLine3;
getline(inFile, dummyLine);
// Declares Array
float values[nLin][nCol];
//Fill Array with -1
for(int l=0; l<nLin; l++)
for(int c=0; c<nCol; c++)
values[l][c] = -1;
// reads file to end of *file*, not line
while(!inFile.eof()) {
for (int i=0; i<nCol; i++) {
inFile >> values[i][nLinActual];
}
i=0;
++nLinActual;
}
// Check what's happening
cout << endl;
for(int l=0; l<nLin; l++){
for(int c=0; c<nCol; c++){
cout << values[l][c] << "\t";
outFile << values[l][c] << "\t";
}
cout << endl;
outFile << endl;
}
inFile.close();
outFile.close();
return 0;
最佳答案
最简单的方法是使用 vector :
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
int main()
{
std::fstream in("in.txt");
std::string line;
std::vector<std::vector<float>> v;
int i = 0;
while (std::getline(in, line))
{
float value;
std::stringstream ss(line);
v.push_back(std::vector<float>());
while (ss >> value)
{
v[i].push_back(value);
}
++i;
}
}
更新:您说您需要使用原始 C 数组来完成它。当然,这是可以做到的:
int main()
{
std::ifstream in("in.txt");
std::string line;
float v[9][10];
int i = 0, k = 0;
while (std::getline(in, line))
{
float value;
int k = 0;
std::stringstream ss(line);
while (ss >> value)
{
v[i][k] = value;
++k;
}
++i;
}
}
关于C++ 从 .txt 中读取浮点值并将它们放入一个未知大小的二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19102640/