Reading data from file into array

后端 未结 3 985
鱼传尺愫
鱼传尺愫 2020-12-18 05:47

I am trying to read specific data from a file into two 2D arrays. The first line of data defines the size of each array so when I fill the first Array i need to skip that li

3条回答
  •  清酒与你
    2020-12-18 06:04

    You're reading into seat once then filling the array with this value. Then you're reading into seat again, and filling the entire array with this new value.

    Try this:

    int CurRow = 0;
    int CurCol = 0;
    while ( (inFile >> seat) && (CurRow < FC_Row)) {
      firstClass[CurRow][CurCol] = seat;
      ++CurCol;
      if (CurCol == FC_Col) {
        ++CurRow;
        CurCol = 0;
      }
    }
    if (CurRow != FC_Row) {
      // Didn't finish reading, inFile >> seat must have failed.
    }
    

    Your second loop should use economyClass not firstClass

    The reason for switching the loop around like this is error handling, which is simplified when the loop exits upon error. Alternatively you could keep the for loops, use infile >> seat in the inner loop, but you'd then have to break out of two loops if reading failed.

提交回复
热议问题