C++从.txt读取浮点值,并将它们放入未知大小的 2D 数组中

C++ read float values from .txt and put them into an unknown size 2D array

本文关键字:未知 数组 2D 读取 txt C++      更新时间:2023-10-16

在C++中,我想读取一个带有浮点数列的文本文件并将它们放在二维数组中。

第一行将是第一列,依此类推。

数组的大小是未知的,这取决于可能变化的行和列。

我尝试过使用"getline","inFile>>",但我所做的所有更改都存在一些问题。

例如,有没有办法在值存在后删除不必要的行/行?

文件如下所示(+/-):

  • 字符 "\t" 字符 "\t" 字符 ""
  • 浮点数 "\t" 浮点数 "\t" 浮点数 "\
  • t" 浮点数 ""
  • 浮点数 "\t" 浮点数 "\t" 浮点数 "\
  • t" 浮点数 ""
  • 浮点数 "\t" 浮点数 "\t" 浮点数 "\
  • t" 浮点数 ""

谢谢

到目前为止,我有这个:

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; 

}

最简单的方法是使用向量:

#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;
    }
}
我认为

这可能会对您有所帮助。使用类型 float 的向量,因为您不知道项数的计数。此代码假定您在每行都有一个用空格分隔的float数字。

fstream fs;
fs.open("abc.txt",ios::in);
vector<vector<float>> floatVec;
string strFloat;
float fNum;
int counter = 0;
while(getline(fs,strFloat))
{
    std::stringstream  linestream(strFloat);
    floatVec.push_back(std::vector<float>());
    while(linestream>>fNum)
        floatVec[counter].push_back(fNum);
    ++counter;
}