我有一个程序使用二维数组来存储一些值。我有两个问题。首先我的程序没有正确地从我的文本文件中读取数据。当它打印出数组中的数字时,我得到的都是零。我的代码有什么问题?
#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();
}
}
我的第二个问题是单个二维数组可以同时包含 char 数据类型和 int 类型吗?还是我必须将 .txt 文件中的所有数据作为字符获取,然后将数字转换为整数?
将不胜感激如何执行此操作的示例。
最佳答案
首先是错误:您的 ary
声明没有保留任何空间。您必须为两个维度提供一个数字。
其次,您可以通过将两个不同的东西放在一个结构中来创建一个数组。
struct It
{
char c;
int i;
};
It ary [MAX_ROWS][13];
关于c++ - 数组不从 C++ 中的文件读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18989321/