c++ - 数组不从 C++ 中的文件读取数据

标签 c++ arrays file-io

我有一个程序使用二维数组来存储一些值。我有两个问题。首先我的程序没有正确地从我的文本文件中读取数据。当它打印出数组中的数字时,我得到的都是零。我的代码有什么问题?

#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/

相关文章:

c++ - 为什么数组中的数据被删除后还能用?

c++ - 驻留内存增加,而 valgrind 未显示任何泄漏

javascript - 如何从数组中提取特定值?

javascript - 循环遍历 JSON 数组并替换为 NULL 的值

java - 如何在java中查找数组中的元素数量?

c++ - 将文件数据从服务器返回到客户端 - reg

c++ - 函数所需的总堆栈大小与变量范围有何关系?

c++ - 在 Eclipse 中找不到用于连接 MySQL 的 C++ 代码的库

c++ - 为什么要在函数中使用 *&param ?

perl - 使用 Perl 将 PDF 文件字节写入文件?