c++ - 我是填错了这个数组还是输出错了?

标签 c++ arrays

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

数据:

(我将每行的第一个数字更改为 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;
}

最佳答案

你填错了。

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

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

在第一个内循环中,您会将 2, 1, 1, 1, 3, 0 读入 airplane[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] ;

关于c++ - 我是填错了这个数组还是输出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5266630/

相关文章:

c++ - 试图找出为什么我的代码保持无限循环

c++ - 代码::Blocks, and C++ Compiler problem. cant compile a header

python - 如何轻松地将 CLI 输出转换为字符串

ios - 避免类对象数组中的重复 Swift 3

c - 释放结构中的数组

javascript - 如何在此 jQuery .each() 循环中解析 "undefined"?

javascript - 将对象转换为包含对象作为元素 0 的数组

c++ - 如何在 Win8/Metro/WinRT 中获取 DocumentsLibrary 的绝对路径?

c++ - 分配给 `char* x = new char[32]` 的内存过多

iphone - 为 iOS 设备创建唯一标识符?