繁体   English   中英

如何从文件读取输入?

[英]How do I read input from files?

我正在尝试将文件中的输入读入数组。 我似乎已经完成了必要的工作,但是代码却无法正常工作。 请告诉我我要去哪里错了。 这是我的代码:

int pb[10][10];
int i,j,n;
string ip_filename = string("pro.txt");

    ifstream fil1;

    fil1.open(ip_filename.c_str());

// to store the probabilities of the nodes
for(i=0;i<num_rows;i++)
    for(j=0;j<num_cols;j++)
    fil1 >> pb[i][j];

fil1.close();

for(i=0;i<num_rows;i++)
{
for(j=0;j<num_cols;j++)
    cout<<pb[i][j]<<" ";
cout<<endl;
}

文本文件与cpp文件位于同一目录中。 打印输出时,无论文件中的值如何,它仅打印0。

文件中的值存储如下

0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15

之前在代码中定义了num_rowsnum_cols ,它们的值均为4。

这段代码的pro.txt格式对您来说非常适合我,如下所示:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    int num_rows = 4;
    int num_cols = 4;
    int pb[10][10];
    int i,j,n;
    string ip_filename = string("pro.txt");

    ifstream fil1;

    fil1.open(ip_filename.c_str());

    // to store the probabilities of the nodes
    for(i=0;i<num_rows;i++)
        for(j=0;j<num_cols;j++)
            fil1 >> pb[i][j];

    fil1.close();

    for(i=0;i<num_rows;i++)
    {
        for(j=0;j<num_cols;j++)
            cout<<pb[i][j]<<" ";
        cout<<endl;
    }

}

我的建议是确保pro.txt与.exe文件位于同一目录中。 如果使用IDE生成此代码,则该目录可能与.cpp文件不同。

通常,执行此类操作的最简单方法是将数据存储在平面数组(甚至更好的是std::vector )中,并使用简单的算法按行和列访问元素。 这使事情变得简单得多。

一个包装器可能看起来像这样:

template<int ColumnCount>
class MyMatrix {
public:
    template<class T>
    MyMatrix(T & begin, T & end) : data(begin, end) {}

    int getItem(int i, int j) const {
        return data[i*ColumnCount+j];
    }
private:
    std::vector<int> data;
};

然后,您可以像这样读取数据:

std::ifstream file1("pro.txt");
std::istream_iterator<int> begin(file1);
std::istream_iterator<int> end;

MyMatrix<4> m(begin, end);

使用fstream时,为了进行可靠的编码,最好在open()之后使用is_open()检查错误情况,并在operator <<()之后使用fail()检查错误情况。
此外,更喜欢

while(getline(fil1, lineString))
{
  ...;
}

因此您可以检查正在阅读的行以及出了什么问题。

检查愉快...

如我所见,您想从文件中加载矩阵。 在文件中,您的值存储为字符串,并用空格分隔。 因此,您应该加载文件,逐行读取文件,将字符串分成字符串数组,然后将值从string转换为int并将其存储到矩阵中。

每次操作后流的状态如何? 未经验证,您不应该阅读。 而且,您不应该在未确认开放有效的情况下进行阅读:

ifstream fill( ip_filename.c_str() );
if ( !fill ) {
    //  error handling, open failed...
}

之后,我同意逐行阅读的建议:

int row = 0;
string line;
while ( getline( fill, line ) && row < size( pb ) ) {
    istringstream sLine( line );
    int col = 0;
    int tmp ;
    while ( sLine >> tmp && col < size( pb[ row ] )) {
        pb[row][col] = tmp;
        ++ col;
    }
    if ( col != size( pb[ row ] ) ) {
        //  Input error, too few entries
    } else if ( sLine >> ws && sLine.get() != EOF ) {
        //  Input error, garbage at end of line <row>
    }
    ++ row;
}
if ( row != size( pb ) ) {
    //  Input error, garbage at end of file
}

或者,您可以根据输入动态决定尺寸:

std::vector<std::vector<int> > pb;
ifstream fill( ip_filename.c_str() );
if ( !fill ) {
    //  error handling, open failed...
}
string line;
while ( getline( fill, line ) ) {
    std::vector<int> tmp1;
    istringstream sLine( line );
    int tmp2;
    while ( sLine >> tmp2 ) {
        tmp1.back().push_back( tmp2 );
    }
    if ( sLine >> ws && ! sLine.eof() ) {
        //  input error: non-numeric data in line
    } else if ( ! pb.empty() && tmp1.size() != pb.back().size() ) {
        //  input error : inconsistent number of columns.
    }
}
//  Check here if square matrix required.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM