在一维数组中输出所有数据
output all data in one dimensional array
我刚刚从一个文本文件中读取数据到一个单维数组中。我的"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
相关文章:
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 使用 python 或 c ++ 中的 sql 根据输入数据输出输出示例
- 尝试从 txt 文件中读取两条数据并输出它们 [C++]
- 将多个效果与 libSox 链接并读取输出数据的正确方法
- 如何将函数的输出数据存储在文本文件中
- 如何从amd gpus的显示输出中获取图像数据
- 自定义堆栈上 std::string 数据的输出
- 如何从文本文件输出数据?(学生成绩单计划)
- 为什么我的数据/输出文件为空?
- C++:如何将数据输出到多个.dat文件
- C++:将存储在List容器中的数据输出到文本文件中
- .wav C++数据输出不正确
- C++:模拟餐饮公司计费程序-无法将错误数据输出到错误文件
- 使用iomanip将数据输出格式化为具有Qt的文本文件
- matPutVariable:尝试将数据输出到mat文件时出错(matrix::serialize::WrongSize
- 如何使用类似于gcc-xml的clang生成元数据输出
- 如何使用Python从UART Beaglebone获取数据输出
- GP635T gps传感器的数据输出
- 如何在Windows控制台中将数据输出到自定义流(3>4>等)?
- 流数据输出问题