繁体   English   中英

数组无法从C ++文件中读取数据

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM