我將一個布爾矩陣(ROW * ROW)保存爲.txt文件(0,1格式)。如何讀取文件
如何從文件中讀取矩陣?我在下面寫了代碼,但是我將讀取結果與文件進行比較,並且數組結果與文件不匹配。有人能告訴我我寫錯了嗎?或者有沒有更簡單的方法來讀取矩陣文件?
bool **results = new bool*[ROW];
for(int i=0;i<ROW;i++){
results[i] = new bool[ROW];
}
ifstream infile;
infile.open ("FRM.txt");
string line;
int row=0;
if (infile.is_open())
{
while (infile.good())
{
getline(infile,line);
istringstream iss(line);
int col=0;
while(iss)
{
string word;
iss >> word;
int number = atoi(word.c_str());
if(number==1){
results[row][col] = true;
}
else{
results[row][col] = false;
}
col++;
}
row++;
}
}
infile.close();
請的std ::法院字。 – 2013-04-08 06:12:28
我知道問題所在。當我保存矩陣時,每個數字後面都有一個空格。所以當我讀一行時,我得到了類似「0 1 1 1」的內容,最後一個空格導致了錯誤。因爲「字符串」實際上會處理「」,並將其視爲整數0. – 2013-04-08 06:26:36