如何从文件中读取输入?

发布于 2024-10-24 01:36:36 字数 683 浏览 4 评论 0原文

我正在尝试将文件中的输入读取到数组中。我似乎已经完成了必要的工作,但代码没有按预期工作。请告诉我哪里错了。这是我的代码:

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。

I am trying to read input from file into an array. I seem to have done the needful, yet the code is not working as it should. Please tell me where am i going wrong. This s my code:

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;
}

The text file is in the same directory as the cpp file is. While printing the output, it just prints 0 irrespective of the value in the file.

The values in the file is store as follows

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

num_rows and num_cols are defined previously in the code, both have the value 4.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

惜醉颜 2024-10-31 01:36:36

这段代码对我来说效果很好,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 文件位于不同的目录。

This code works perfectly fine for me with pro.txt formatted like you show:

#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;
    }

}

My suggestion would be to ensure that pro.txt is in the same directory as you .exe file. If you are using an IDE to build this code it is likely a different directory from your .cpp files.

花想c 2024-10-31 01:36:36

使用 fstream 时,为了实现鲁棒性编码,最好在 open() 之后使用 is_open() 检查错误条件,在operator<<() 之后使用fail() 检查错误条件。
此外,

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

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

快乐检查...

When using fstream, for robust coding, it is best to check error conditions with is_open() after open() and fail() after operator<<().
Furthermore, prefer

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

so you can check what line you're reading in and what is going wrong.

Happy checking...

泪意 2024-10-31 01:36:36

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

As i see you want to load a matrix from a file. In file your values are stored as string separated by space. So you should load your file, read the file line by line, separate your string into a string array and the convert your values from string to int and store them into your matrix.

呢古 2024-10-31 01:36:36

通常,执行此类操作的最简单方法是将数据存储在平面数组中(或者更好的是 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);

Usually the simplest way to do these kinds of things is to store the data in a flat array (or even better a std::vector), and the use simple arithmetics to access the elements by rows and columns. This makes things much simpler.

A wrapper for this could look like this:

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;
};

Then you can read the data like this:

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

MyMatrix<4> m(begin, end);
肥爪爪 2024-10-31 01:36:36

每次操作后流的状态是什么?你不应该这样
读取而不验证。而且你不应该在没有阅读的情况下阅读
验证开放工作:

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.

What is the status of the stream after each operation? You shouldn't be
reading without verifying. And you shouldn't be reading without having
verified that the open worked:

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

After that, I would agree with the suggestion of reading line by line:

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
}

Alternatively, you could decide on the dimensions dynamically, according
to the input:

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文