c ++读取txt文件并将其存储在char中的矩阵char中

时间:2014-01-17 21:41:41

标签: c++

我需要读取一个txt文件并将其存储到矩阵中(我们假设它是一个2x2矩阵)。我对下面的代码有疑问(我把它简化为更加清晰):

#include<stdexcept>
#include<string>
#include<fstream>
using namespace std;

class A{

private:

int **m;

void allocate_mem(int ***ptr){
    *ptr = new int *[2];
    (*ptr)[0] = new int[2*2];
    for(unsigned i = 1; i < 2; i++)
        (*ptr)[i] = (*ptr)[0] + i*2;
}

void read_file(string file_input){
    ifstream fin(file_input.c_str());
    allocate_mem(&m);
    char a;
    for(unsigned i = 0; i < 2; i++) {
        for (unsigned j = 0; j < 2; j++) {
            a = fin.get();
            if(a=="X"){     
 //ISO C++ forbids comparison between pointer and integer [-fpermissive]
                m[i][j] = 1;
            }else{
                m[i][j] = 0;
            }
        }       
    }
    fin.close();        
}

public:

A(){
    throw logic_error("Error!");
}

A(string file_name){
    read_file(file_name);
}

~A(){
    delete[] m[0];
    delete[] m;
}

};

input.txt中

XX
 X

我想存储一个2x2矩阵,其元素是:

11
01

1 个答案:

答案 0 :(得分:0)

解决方案很简单:编写C ++而不是C

使用标准容器代替手动内存管理。 另外,如果您在编译时知道数据的大小,为什么还要使用动态内存?

int m[2][2];

void read_file(const std::string& file_input) {
    ifstream fin(file_input.c_str());
    char a;

    if( !fin ) throw;

    for (std::size_t i = 0; i < 2; i++) {
        for (std::size_t j = 0; j < 2; j++) {
            a = fin.get();
            if (a == 'X') { // '' is for characters, "" for strings. Thats why the compiler
                m[i][j] = 1;// warns you (You are comparing the char[], which is decayed to
            } else {        // char*, with the integer value of the char variable)
                m[i][j] = 0;
            }
         }
     }
//Close not needed (RAII)
}