8

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

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

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

我尝试过使用“getline”、“inFile >>”,但我所做的所有更改都有一些问题。

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

文件看起来像这样 (+/-):

  • 字符 "\t" 字符 "\t" 字符 "\n"
  • 浮动 "\t" 浮动 "\t" 浮动 "\t" 浮动 "\n"
  • 浮动 "\t" 浮动 "\t" 浮动 "\t" 浮动 "\n"
  • 浮动 "\t" 浮动 "\t" 浮动 "\t" 浮动 "\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; 

}

4

2 回答 2

8

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

#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;
    }
}
于 2013-09-30T20:00:07.873 回答
2

我想这可能会对你有所帮助。使用类型向量的向量,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;
}
于 2013-09-30T19:56:54.803 回答