[英]array not reading data from file in c++
我有一個使用2d數組存儲一些值的程序。 我有兩個問題。 首先,我的程序無法從我的文本文件中正確讀取數據。 當它打印出數組中的數字時,我得到全零。 我的代碼有什么問題?
#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文件中的所有數據作為字符獲取,然后將數字轉換為整數?
一個如何做到這一點的例子將不勝感激。
首先是錯誤:您對ary
的聲明不保留任何空間。 您必須為兩個尺寸都給出一個數字。
其次,可以通過將兩個不同的事物放入一個結構中來構成它們。
struct It
{
char c;
int i;
};
It ary [MAX_ROWS][13];
沒有與以下數組關聯的內存:
int ary [][13];
而且我想知道為什么您的編譯器不會抱怨諸如“'ary'的存儲大小未知”之類的東西 。 無論如何,您應該改用std::vector
。 關於: “單個2d數組可以同時包含char
數據類型和int
類型嗎?” 〜>您可以定義自定義類型,或者可以使用:
std::vector< std::vector< std::pair<char, int> > > grades;
盡管在看這個成對的矩陣時……似乎有些錯誤,而且我敢肯定,無論您要完成什么,都有一種更簡單的方法。
也請嘗試避免使用全局變量。 您使用它們的方式會使代碼分解為功能變得毫無用處。 對於C ++,您的代碼過於程序化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.