正在从文本文件创建2d int表.输出可能是内存块

Creating 2d int table from text file. Output being (probably) blocks of memory

本文关键字:输出 内存 int 文本 文件创建 2d      更新时间:2023-10-16

我一直在尝试根据文本文件中的内容创建一个2d表。文本文件本身是20x20,仅由"0"answers"1"组成,没有任何空格,行之间仅使用enter。这是我的代码:

#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main() {
    int z;
    int tabLab[20][20];

    //Drawing default map
    FILE * pLab;
    pLab = fopen ("labirynt.txt", "r");
        while((z = fgetc(pLab)) != EOF) {
            if(z == '0') {
                cout << (char)219 << (char)219;
            } else if (z == '1') {
                cout << "  " ;
            } else if (z=='n') {
                cout << endl;
            }
    //Saving default map to 2d table
        }
            ifstream plLab;
                plLab.open("labirynt.txt");
                if(plLab.good()==true)
                {
                    for(int j = 0; j < 21; j++)
                    {   
                        for(int i = 0; i < 20; i++)
                        {   
                            plLab>>tabLab[j][i];
                        }
                    }
                }
    cout << endl;
    //Checking if table has been created correctly 
    for (int k = 0; k < 21; k++) {
        for(int l = 0; l < 21; l++) {
            cout << tabLab[k][l];
        }
        cout << endl;
    }
}

我一直在努力解决输出的问题,它是一个大的随机数,但到目前为止我还没有设法修复它。

让我们尝试一个更简单的案例。(你应该总是从简单开始,然后逐渐发展到复杂。)

laborynt.txt:

1011

代码中:

int n;
plLab.open("labirynt.txt");
plLab>>n;
cout << n << endl;

这产生:

1011

很明显,代码不知道您打算只读取文件的一个字符。因此,当你试图以这种方式读取整个文件时,你读到了末尾,但未能设置表中大多数条目的值,因此它们包含随机垃圾。

有几种方法可以解决这个问题,这是最简单的方法之一:

int n;
char c;
plLab.open("labirynt.txt");
plLab >> c;
n=0;
if(c=='1')
  n=1;
cout << n << endl;

由此,您可以构建到表格填充器。

您的代码存在一些问题,但最重要的是,它缺乏对输入数据的一些错误检查,并且您在循环中使用了错误的边界。看看这个:

#include <iostream>
#include <fstream>
#include <string>
#define ROWS 20
#define COLS 20
int main() {
    int tabLab[ROWS][COLS];         // You are using int, but till now you have to store only 0 or 1...
// ---------- Read the input file, populating the 2d array --------------
    char inFileName[] = "labyrinth.txt";       
    char c;
    std::ifstream inFileLab;
    inFileLab.open(inFileName, std::ios_base::in);
    if ( !inFileLab.good() ) {
        std::cerr << "Error: I can't open the file " << inFileName << std::endl;
        exit(1);
    }
    for ( int i = 0; i < ROWS; i++) {
        for ( int j = 0; j < COLS; j++ ) {
            if ( !inFileLab.get(c) ) {
                std::cerr << "Error: I can't read element (" << i + 1 << ", " << j + 1 << ") in file " << inFileName << std::endl;
                exit(2);
            }
            if ( c == '0' ) 
                tabLab[i][j] = 0;
            else if ( c == '1' )
                tabLab[i][j] = 1;
            else {
                std::cerr << "Error: Wrong value read for element (" << i + 1 << ", " << j + 1 << ") in file " << inFileName << std::endl;
                exit(3);        // You can choose to set table[i][j] = 0 or 1 and continue;
            }
        }
        if ( i < ROWS - 1) {    // if the last row doesn't end with a newline it's not a big deal.
            if ( !inFileLab.get(c) ) {  
                    std::cerr << "Error: Abnormal line termination at row " << i + 1 << " in file " << inFileName << std::endl;
                    exit(4);                        
            }
            if ( c != 'n') {
                std::cerr << "Error: Line " << i + 1 << " is too long in file " << inFileName << std::endl;
                exit(5);                    
            }
        }
    }                           // The file can be bigger, I just ignore the extra data
    inFileLab.close();          //  and close the file (that could be tested too)
// --------------------- Show the 2d array -------------------------------
    const char block = 219;
    for ( int i = 0; i < ROWS; i++) {
        for ( int j = 0; j < COLS; j++ ) {      // Like in your program, if t[i][j] == 1 you print space, blocks otherwise
            if ( tabLab[i][j] ) std::cout << "  ";  // Imho, the opposite would be better...
            else std::cout << block << block;
        }
        std::cout << std::endl;
    }
// -------------------- Save the 2d array in another file -------------------
    char outFileName[] = "labyrinth_copy.txt";       
    std::ofstream outFileLab;
    outFileLab.open(outFileName, std::ios_base::out);
    if ( !outFileLab.good() ) {
        std::cerr << "Error: I can't open the output file " << outFileName << std::endl;
        exit(5);
    }
    for ( int i = 0; i < ROWS ; i++) {
        for ( int j = 0; j < COLS; j++ ) {
            outFileLab << tabLab[i][j];
            if ( !outFileLab.good() ) {
                std::cerr << "Error: I can't save element (" << i + 1 << ", " << j + 1 << ") in file " << outFileName << std::endl;
                exit(6);
            }
        }       
        outFileLab << std::endl;
        if ( !outFileLab.good() ) {
            std::cerr << "Error: I could save only " << i << "rows out of " << ROWS << " in file " << outFileName << std::endl;
            exit(7);
        }
    }                           // The file is closed automatically when execution goes out of scope
// --------------------------------- Everything went fine ---------------------------
    return 0;
}

你可以做更多的改进。

如果在文本文件中写入不带空格的数字,如下所示:

fout<<1<<0<<1<<0

当你把它读到int时,你会得到整个1010,因为字符串流一直读到第一个空白,它将是行的末尾。

您可以通过多种方式来解决它:例如,通过在字符后读取字符:

//inside the read loop
char temp;
plLab>>temp;
tabLab[j][i]= (temp == '0') ? 0 : 1;