在一维数组中输出所有数据

output all data in one dimensional array

本文关键字:数据 输出 一维数组      更新时间:2023-10-16

我刚刚从一个文本文件中读取数据到一个单维数组中。我的"for"语句没有从数组输出数据。我想输出整个数组来验证所有的数据都在那里。但是,当我输出单个单元格时,数据将输出到屏幕上。我做错了什么?提前感谢!

#include <iostream>
#include <fstream>
#include <iomanip>
int main()
{
  const int MAX_CELLS = 500;      
  int count = 0;         
  double Vehicles[MAX_CELLS];   
  ifstream vehicleFile;           
  char type; 
  string license; 
  double charge; 
  vehicleFile.open ("VEHICLE.txt");   
  if (!vehicleFile)            
     cout << "Error opening vehicle file " << endl;
     vehicleFile >> type >> license ;              // priming read

     while (vehicleFile) {                         // while the read was successful
          cout << count << " "  << license << endl;    // FOR DISPLAY ONLY
          vehicleFile >> Vehicles[count];              // read into array
          count++;                                     // increment count
          vehicleFile >> type >> license;              // read next line
     }   
    cout << showpoint << fixed << setprecision(2); 

    for ( count; count < MAX_CELLS; count++) {
          cout << "Array #" << count << "is: ";        // OUTPUT ARRAY 
          cout << Vehicles[count] << endl; 
    }

    cout << Vehicles[8];       // READS DATA IN CELL 

    vehicleFile.close(); 

    system ("pause"); 
    return 0;       
}

count需要像这样重置:

for ( count = 0; count < MAX_CELLS; count++) {
      cout << "Array #" << count << "is: ";        // OUTPUT ARRAY 
      cout << Vehicles[count] << endl; 
}

在前一个循环中,您为每个记录增加count,因此当它到达for循环时,它已经被设置为最后一个记录的索引。虽然你真正想做的是使用一个新的变量,只迭代count次:

for ( int i = 0; i < count ; ++i) {
      cout << "Array #" << i << "is: ";        // OUTPUT ARRAY 
      cout << Vehicles[i] << endl; 
}

当你读取你的数据时,你也没有检查MAX_CELLS。所以如果你的文件有多于MAX_CELLS的数据,那么你就会有未定义的行为

count在while循环后继续存在,因此它将是while循环完成后的结束值。然后,当它进入for循环时,它将从该值

开始

考虑一下:

int count = 0
while(count < 10)
    count++
std::cout << "count is: " << count << std::endl;
for (count; count < 15; count++)
   std::cout << "now count is: " << count << std::endl

你的输出将是:

count is: 10
now count is: 11
now count is: 12
now count is: 13
now count is: 14
now count is: 15

您需要在for循环中或之前重置计数。

在for循环中,您不会重新初始化count (count = 0)。

为了使生活更容易,并避免这些类型的逻辑错误,尝试:

for ( int i = 0; i < MAX_CELLS; ++i ) {
    cout << "Array #" << i << "is: ";        // OUTPUT ARRAY 
    cout << Vehicles[i] << endl; 
}

目前,看起来count已经大于或等于MAX_CELLS