我填写这个数组错了或输错了吗?

时间:2011-03-10 22:21:11

标签: c++ arrays

我正在开发一个用文本文件中的数据填充数组的程序。当我输出数组时,它的内容不是我认为读入它的顺序。我认为问题是在一个for循环中将数据输入数组或将数组输出到iostream。谁能发现我的错误?

数据

(我将每行中的第一个数字改为2-31,以区别于0和1) enter image description here

输出

enter image description here

代码

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main()
{
    ifstream inFile;
    int FC_Row, FC_Col, EconRow, EconCol, seat, a, b;

    inFile.open("Airplane.txt");

    inFile >> FC_Row >> FC_Col >> EconRow >> EconCol;

    int airplane[100][6];

    int CurRow = 0;
    int CurCol = 0;

    while ( (inFile >> seat) && (CurRow < FC_Row)) 
    {
     airplane[CurRow][CurCol] = seat;
     ++CurCol;
      if (CurCol == FC_Col)
       {
       ++CurRow;
       CurCol = 0;
       }
    }


while ( (inFile >> seat) && (CurRow < EconRow)) 
{
 airplane[CurRow][CurCol] = seat;
 ++CurCol;
  if (CurCol == EconCol)
    {
     ++CurRow;
     CurCol = 0;
    }
 }

    cout << setw(11)<< "A" << setw(6) << "B"
    << setw(6) << "C" << setw(6) << "D"
    << setw(6) << "E" << setw(6) << "F" << endl;
    cout << " " << endl;

    cout << setw(21) << "First Class" << endl;
    for (a = 0; a < FC_Row; a++)
    {
        cout << "Row " << setw(2) << a + 1;
        for (b = 0; b < FC_Col; b++)
        cout << setw(5) << airplane[a][b] << " ";

        cout << endl;
    }

    cout << setw(23) << "Economy Class" << endl;
    for (a = 6; a < EconRow; a++)
    {
        cout <<"Row " << setw(2)<< a + 1;
        for (b = 0; b < EconCol; b++)
        cout << setw(5) << airplane[a][b] << " ";

        cout << endl;
    }


    system("PAUSE");
    return EXIT_SUCCESS;
}

4 个答案:

答案 0 :(得分:1)

你填错了。

for (a = 0; a < 100; a++)    
    for (b = 0; b < 6; b++)

上面的循环与文件的第一行不匹配,每行没有6个元素。

在第一个内循环中,您将2, 1, 1, 1, 3, 0读入飞机[0]。

编辑:修复。

for (a = 0; a < FC_Row; a++)    
    for (b = 0; b < FC_Col; b++)
        inFile >> airplane[a][b] ;

for (a = 0; a < EconRow; a++)    
    for (b = 0; b < EconCol; b++)
        inFile >> airplane[a+FC_Row][b] ;

答案 1 :(得分:1)

填充数组的代码:

   for (a = 0; a < 100; a++)    
        for (b = 0; b < 6; b++)
            inFile >> airplane[a][b] ;

假设每行有6列,没有,前6行只有4行。

答案 2 :(得分:0)

所以你要填写100x6数组,但前几行数据只有4列数据。

更好的方法是这样的:

 for (a = 0; a < 100; a++)    
        for (b = 0; b < 6; b++)
        {
          char c;
          inFile>>c;
          if (c is new line){
            break;
          }

          //fill in the 2d array
        }

答案 3 :(得分:0)

这里的正确方法是使用std :: getline一次读取一行。然后解析每一行,类似于你的方式,虽然你可能想要使用向量而不是二维数组。

如果你有一个矢量矢量,你会发现内部矢量不需要都具有相同的大小,事实上它们不应该在你的情况下。

实际上,我没有得到的是你正在阅读EconRow和EconCol的值,但是还要对你的数组大小进行硬编码。

使用矢量,您可以灵活地将其设置为您已阅读的值。

相关问题