我有一個程序使用2d數組來存儲一些值。我有2個問題。首先,我的程序沒有正確讀取我的文本文件中的數據。當它打印出數組中的數字時,我得到所有的零。我的代碼有什麼問題?數組不從C++中的文件讀取數據
#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std;
int ary [][13];
ofstream OutFile;
ifstream infile("NameAvg.txt");
//function prototype
void ReadIt (int [][13]); // Function call ReadIntoArrayByRows(ary);
void WritePrintOutArray (int [][13]);
int main()
{
//open/creates file to print to
OutFile.open ("MyOutFile.txt");
// Title and Heading
OutFile << "\nName and grade average\n";
cout << "Name and grade average.\n\n";
// Open and Reads .txt file for array
ReadIt(ary);
OutFile<<"\n-----------------------------"<<endl;
cout<<"\n-----------------------------"<<endl;
WritePrintOutArray(ary);
OutFile<<"\n-----------------------------"<<endl;
cout<<"\n-----------------------------"<<endl;
//closes .txt file
OutFile.close();
cin.get();
cin.get();
return 0;
}
void WritePrintOutArray(int ary[][13])
{
int col,
row;
for(row=0;row<2;row++)
{
for(col=0;col<8;col++)
{
ary[2][13];
cout<<ary[row][col];
OutFile<<ary[row][col];
}
cout<<endl;
OutFile<<endl;
}
}
void ReadIt(int ary[][13])
{
int col,
row=0;
while(infile>>ary[row][0])
{
for(col=1;col<13;col++)
{
infile>>ary[row][col];
row++;
}
infile.close();
}
}
我的第二個問題是單個2d數組可以同時擁有char數據類型和int類型嗎?或者我必須將.txt文件中的所有數據作爲字符,然後將這些數字轉換爲整數?
如何做到這一點的例子將不勝感激。
take infile.close();在while循環之外。 – hasan83
你認爲這行代碼要做什麼? '進制[2] [13];'?如果您使用G ++或CLANG進行編譯,則可能需要嘗試打開'-Wall'。 – kfsone