【问题标题】:Assigning data from file to matrix C++将文件中的数据分配给矩阵 C++
【发布时间】:2012-05-20 00:12:23
【问题描述】:

大家好, 我是 C++ 的初学者。 我想要达到的目标是安静的愚蠢。但我不明白/不明白错误在哪里。 如有任何 bluecode 帮助,我将不胜感激。

所以...我想分配文件“REL”的内容,这是一个46x2的矩阵[无空行]:

28 28
28  6
28 21
28 30
28 16
22 22
22 33
22 9
39 39
39 32
39 46
39 10
39 24
36 36
36 7
36 43
36 23
11 11
11 26
11 41
15 15
15 17
15 45
15 29
15 40
3 3
3 37
3 42
3 34
3 2
35 35
35 4
35 14
35 44
35 18
13 13
13 12
13 25
13 5
13 1
13 8
13 31
20 20
20 27
20 19
20 38

而我的 C++ 代码是:

    include <stdlib.h>
    include <malloc.h>
    include <iostream>
    include <fstream>

    using namespace std;

    void allocateMatrix(int **& A, int row, int col)
    {
        int i;
        A = new int*[row];
        for (i=1; i<=col; i++)
            A[i] = new int[col];
    }

    void ReadData(int **& A, int row, int col) // read data from file
    {  
    int i,j;
    ifstream REL1;
    REL1.open ("REL");  // open file for reading                
    for(i=1;i<=row;i++)   // row loop
    {
        for(j=1;j<=col;j++)  // column loop
        {
            REL1 >> A[i][j]; // read data into matrix
        }
        REL1.close(); // close the file                
    }
    }

    void Display(int **& A, int row, int col) // display matrix
    { 
    int i,j;
    for(i=1;i<=row;i++)
    {
        for(j=1;j<=col;j++)
        { 
            cout << A[i][j] << "\t ";  // display numbers
        }
        cout << endl;
    }    
    }

    void Cero(int **& A, int row, int col) // display matrix
    {
    int i,j;
    for(i=1;i<=row;i++)
    {
        for(j=1;j<=col;j++)
        {
            A[i][j]=0;
        }
    }   
    }   

    int main()
    {
    int tm,rowR,colR,rowM,colM,**A,**B; 

    ifstream TM;
    TM.open("TM");
    TM >> tm;
    TM.close();

    rowR = rowM = colM = tm;
    colR = 2;

    allocateMatrix(A, rowM, colM);
    allocateMatrix(B, rowR, colR);
    Cero(A, rowM, colM); 
    //Display(A, rowM, colM);
    ReadData(B ,rowR, colR);
    Display(B, rowR, colR);

    }

并且...当我在 bash 中运行它时,shell 提示我:

28   28  
0    0   
Segmentation fault (core dumped)

提前致谢!!!

【问题讨论】:

  • 不受保护的输入(比如你&gt;&gt;)是一个严重的错误。如果您检查了它的返回值,您会注意到您过于频繁地关闭文件对象。
  • 感谢Kerrek SB,但我无法实现“不受保护的输入(如你>>)”
  • 你不能只说REL1 &gt;&gt; A[i][j];,因为这会丢弃操作的至关重要的返回值。相反,您需要像if (!(REL1 &gt;&gt; A[i][j])) { std::cerr &lt;&lt; "Fatal error!\n"; std::exit(1); } 这样的东西。

标签: c++ arrays file printing


【解决方案1】:
for(i=1;i<=row;i++)   // row loop
{
    for(j=1;j<=col;j++)  // column loop
    {
        REL1 >> A[i][j]; // read data into matrix
    }
    REL1.close(); // close the file                
}

您在阅读第一行后关闭文件。将文件结束行移出循环。

for(i=1;i<=row;i++)   // row loop
{
    for(j=1;j<=col;j++)  // column loop
    {
        REL1 >> A[i][j]; // read data into matrix
    }               
}
REL1.close(); // close the file 

【讨论】:

  • 感谢回复,我也进行了测试,但结果并不令人鼓舞......在 shell 中它向我提示“~/CM$ ./m2 Segmentation fault (core dumped)”
  • 我不是 C++ 的高手,你可以尝试将外部 for 循环运行到 10 或其他数字而不是“行”,然后观察结果吗?我认为问题出在边界上。
  • 感谢 Ismet Alkan,您部分正确。我听从了你的建议,它向我展示了更多的价值观。我尝试了row = 10row = 100 之后,它部分工作......外壳提示我**28 28 28 6 28 21 28 30 28 16 22 22 22 33 22 9 39 39 39 32 39 46 39 10 39 24 36 36 36 7 36 43 36 23 11 11 11 26 11 41 15 15 15 17 15 45 ** 但是...列表是一半,不像矩阵 [46*2] 它似乎 文件中的数据不是通过考虑矩阵来分配的......只是一行的数组
【解决方案2】:

数组索引从 0 开始,而不是 1。

【讨论】:

  • ... 并且 for 循环中的测试应该使用
  • 好的...我测试了你的建议,我仍然得到 " ~/CM$ ./m2 Segmentation fault (core dumped) " 谢谢但我仍然无法弄清楚错误放置的命令......另一种不同的观点来正确假设这一点? 再次 提前致谢
  • 当然,@ScottHunter 先生,我把它和所有的 cmets 一起发布,在这个帖子上,更新。 ` void ReadData(int & A, int row, int col) { int i,j; ifstream REL1; REL1.open ("REL"); for(i=0;i> A[i][j]; } } REL1.close(); } void Display(int **& A, int row, int col) { int i,j; for(i=0;i 文件在原始帖子中,TR 文件仅包含46。提前致谢
  • @DavidAlejandro 请通过更新您的原始问题发布代码。然后它将被正确格式化:)
  • @DavidAlejandro:所以你没有改变 Cero 或 allocateMatrix?
【解决方案3】:

这里有一个典型的、稳健的、虽然不是完美最优的读取输入的通用方法:首先读取每一行,然后将每一行解析为标记。当然可以添加长度检查,这样您就不会尝试读取具有数十亿行的文件,但我将其留给您。

请注意,我们从不明确调用close(),因为这不是必需的。

#include <iostream>
#include <sstream>
#include <iterator>  // for istream_iterator
#include <string>    // for getline and string
#include <vector>    // for vector
#include <cstdlib>   // for exit

namespace
{
    void die(int code, char const * msg)
    {
        std::cerr << msg << std::endl;
        std::exit(code);
    }
}

int main()
{
    std::ifstream tm("TM.txt");

    if (!tm) { die(1, "Could not open file."); }

    std::vector<std::vector<int>> matrix;

    for (std::string line; std::getline(tm, line); )
    {
        std::istringstream iss(line);
        std::vector<int> row(2);

        if (!(iss >> row[0] >> row[1])) { die(1, "Invalid line!"); }

        matrix.push_back(row);
    }

    // done, now use matrix[i][j]
}

在 C++11 中,您可以添加各种小的优化,但现在不要介意。在更一般的设置中,您还可以删除每行仅包含两个元素的限制,而是读取尽可能多的元素,可能会检查最终大小:

std::vector<int> row(std::istream_iterator<int>(iss), std::istream_iterator<int>());
// check that row.size() has the desired value!

最后,您可能希望在外部循环中添加一个计数器,如果行数超出预期(例如,在您的情况下为 46 行),则中止,这样您就不会被巨大的输入文件破坏。

【讨论】:

    【解决方案4】:

    感谢@KerrekSB 的回复。这一级别的 C++ 编程比 C++ 的基本知识领先一步。不过,我尝试了您的建议并按照发布的方式重写了代码:

    #include <stdlib.h>
    #include <malloc.h>
    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <iterator>  // for istream_iterator
    #include <string>    // for getline and string
    #include <vector>    // for vector
    #include <cstdlib>   // for exit
    
    using namespace std;
    
    namespace
    {
        void die(int code, char const * msg)
        {
            std::cerr << msg << std::endl;
        std::exit(code);
        }
    }
    
    void AllocateMatrix(int **& A, int row, int col)
    {
    int i;
    A = new int*[row];
    for (i=0; i<col; i++)
        A[i] = new int[col];
    }
    
    void ReadData(int **& A, int row, int col) // read data from file
    {  
    int i,j,in;
    ifstream REL1;
    REL1.open ("REL");  // open file for reading                
    for(i=0;i<row;i++)   // row loop
    {
        REL1 >> in; // read data into matrix
        for(j=0;j<col;j++)  // column loop
        {
            A[i][j]=in;
        }
    }
    REL1.close(); // close the file                
    }
    
    void Display(int **& A, int row, int col) // display matrix
    { 
    int i,j;
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        { 
            cout << A[i][j] << "\t ";  // display numbers
        }
    }
    cout <<endl;    
    }
    
    void Cero(int **& A, int row, int col) // display matrix
    {
    int i,j;
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            A[i][j]=0;
        }
    }   
    }   
    
    int main()
    {
    int tm,rowR,colR,rowM,colM,**A,**B; 
    
    ifstream TM;
    TM.open("TM");
    TM >> tm;
    TM.close();
    
    rowR = 46; 
    rowM = colM = tm;
    colR = 2;
    
    AllocateMatrix(A, rowM, colM);
    AllocateMatrix(B, rowR, colR);
    Cero(A, rowM, colM); 
    //Display(A, rowM, colM);
    //ReadData(B ,rowR, colR);
    
    
    std::ifstream rel("REL");
    if (!rel) { die(1, "Could not open file."); }
    std::vector<std::vector<int> > matrix;
    for (std::string line; std::getline(rel, line); )
    {
        std::istringstream iss(line);
        std::vector<int> row(2);
        if (!(iss >> row[0] >> row[1])) { die(1, "Invalid line!"); }
        matrix.push_back(row);
    }
    
    
    
    
    Display(B, rowR, colR);
    }
    

    当我执行它时,它会提示:

    Invalid line!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-22
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      相关资源
      最近更新 更多