2013-09-24 48 views
0

我有一個程序使用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文件中的所有數據作爲字符,然後將這些數字轉換爲整數?

如何做到這一點的例子將不勝感激。

+0

take infile.close();在while循環之外。 – hasan83

+0

你認爲這行代碼要做什麼? '進制[2] [13];'?如果您使用G ++或CLANG進行編譯,則可能需要嘗試打開'-Wall'。 – kfsone

回答

1

首先錯誤:您的聲明ary不保留任何空間。您必須必須給出兩個維度的數字。

其次,你可以通過將這些東西放在一個結構中來製作兩個不同的東西。

struct It 
{ 
    char c; 
    int i; 
}; 

It ary [MAX_ROWS][13]; 
+0

所以如果我有99行和13列,我會用ary [99] [13] – user2371621

0

沒有與下面的數組相關的內存:

int ary [][13]; 

,我不知道爲什麼你的編譯器不喜歡的東西抱怨「的‘元’存儲大小是不知道」。無論如何,你應該使用std::vector。至於:「單個二維數組可以同時擁有一個char數據類型和一個int類型?」〜>您可以定義一個自定義類型或者你也可以使用:

std::vector< std::vector< std::pair<char, int> > > grades; 

雖然一邊看着這個矩陣對...有些事情似乎是錯誤的,我敢肯定,無論是你是試圖完成,有一個更簡單的方法。

也儘量避免使用全局變量。你使用它們的方式使你的代碼分解成函數有點無用。您的代碼對於C++來說過於程序化。