【问题标题】:array not reading data from file in c++数组没有从c ++中的文件中读取数据
【发布时间】:2013-09-24 18:30:28
【问题描述】:

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

#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 文件中的所有数据作为字符获取,然后将数字转换为整数?

非常感谢您提供如何执行此操作的示例。

【问题讨论】:

  • 取infile.close();退出while循环。
  • 你希望这行代码做什么? ary[2][13];?如果您使用 G++ 或 CLANG 进行编译,您可能想尝试打开“-Wall”。

标签: c++ arrays file-io


【解决方案1】:

首先是错误:您的ary 声明没有保留任何空间。您必须给出两个维度的数字。

其次,您可以通过将两个不同的东西放在一个结构中来制作一个数组。

struct It
{
    char c;
    int i;
};

It ary [MAX_ROWS][13];

【讨论】:

  • 所以如果我有 99 行和 13 列,我会使用 ary [99][13]
【解决方案2】:

没有与以下数组关联的内存:

int ary [][13];

我想知道为什么你的编译器没有抱怨类似“‘ary’的存储大小未知”。无论如何,您应该改用std::vector。至于:“单个二维数组可以同时保存char 数据类型和int 类型吗?” ~> 您可以定义自定义类型,或者您可以使用:

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

虽然在查看这个配对矩阵时...似乎有些问题,我确信无论您想要完成什么,都有一种更简单的方法。

还要尽量避免使用全局变量。您使用它们的方式使得将代码分解为函数有点无用。你的代码对于 C++ 来说太程序化了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多