2014-01-17 101 views
-2

我需要读取一个txt文件并将其存储到一个矩阵(我们假设它是一个2x2矩阵)。我有下面的代码有问题(我semplified它更夹板):C++读取txt文件并将其存储在矩阵中char char由字符

#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 

我要存储一个2×2矩阵,其elemets是:

11 
01 
+1

发生了什么事?它是否编译?如果是这样,你得到的是什么产出而不是你期望的? – bstamour

+1

if(a ==“X”)''应该是'if(a =='X')'带单引号 –

+0

它不能编译。该错误在代码中//之后指示。 – MBall

回答

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) 
} 
相关问题