文本文件中的C ++ I / O编号

时间:2013-11-03 20:44:49

标签: c++ matrix io

我试图从测试文件中读取数字并将其显示在矩阵中。在文本文件中,每行有一个数字。前两行是矩阵的维数。(3和4)我很难将这些数字的实际数据值分配给矩阵。在这种情况下,值为2到14。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h> 
using namespace std;
#include "Matrix.h"

int main()
{
        CMatrix A(10,10); //set to arbitrary size
        int x;
        int i = 0;
        int number;
        int rowsFile;
        int columnsFile;

        while ( myFile.good()&& myFile.is_open() )
        {
            myFile>>x;  
            if (i==0){ //for row dimension
                rowsFile = x; 
            }

            if (i==1){ //for column dimension
                columnsFile = x;
            }
            cout<<"Value "<<i<<": "<<x<<endl; //displays the values


            if (i>=2){
                for (int r = 0; r < rowsFile; r++)
                {
                    for (int c = 0; c < columnsFile; c++)
                    {
                        A.Value(r,c) = x;
                        myFile>>x;  
                    }
                }
                myFile.close();
            }


            i=i+1;
        }
        myFile.close();

        CMatrix A(rowsFile, columnsFile);
        cout<<endl<< "Rows: "<<A.getNumberOfRows()<<endl;
        cout<< "Columns: "<<A.getNumberOfColumns()<<endl;
        cout<<endl<<A.ToString();
}

这是我输出的显示。 enter image description here

出于某种原因,我注释掉的循环似乎并没有起作用。 任何帮助,将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:2)

虽然由于没有完全理解你要做的事情我无法为你提供完整的解决方案,但我建议你顺利阅读文件的内容并将它们存储在一个向量中,如下例所示:

std::ifstream ifs("file.txt");
std::string line;
std::vector<std::string> lines;
if (ifs.good()) while (getline(ifs, line)) lines.push_back(line);
else throw std::runtime_error("An error occurred while trying to read from file.");

这样可以更轻松地处理数据。

答案 1 :(得分:1)

我建议您重新组织此代码,以便在读取后立即将双精度放入矩阵元素中。

文件io代码可能不完美,但我会从处理元素值的循环中分离行数和列数的读取。

// do not declare i here
int numRows;
int numCols;

std::fstream inputFile("filename", std::in);

if ! (inputFile >> numRows >> numCols) 
{
    // Handle error 
}

// Check that numRows and numCols are acceptable (positive)
// [not shown] 

CMatrix A(numRows, numCols);
if (inputFile)
{
    int elementsRead = 0;
    for (int i = 0; i < numRows; i++)
    {
        for (int j = 0; j < numCols; j++)
        {
            double x;
            if (inputFile >> x)
            { 
                A.Value(i,j) = x;
                ++elementsRead;
            } else {
                // probably an error from too-short file, 
                // token could not be converted to double, etc.
                // handle appropriately
                break;  
            }
        }
    }
}

if (elementsRead != numRows * numCols)
{
    // handle error
}

// Use matrix A
相关问题