从文件读取时崩溃
crash when reading from a file
首先,我想让你知道我是一名大学生(我们的编程教学大纲还没有那么先进)(顺便说一句,我不问我的作业答案等,我只是在练习)。
好的,所以我有 2 个问题
- 我的代码中的某些函数更改了数组的值(当我不希望它时)
- 我真的不知道,但似乎从文件中获取一些值以存储到我的数组中会使程序崩溃,此外,在摆弄了一下代码(我不知道发生了什么变化)之后,它在所述部分不再崩溃,但它仍然在代码执行结束时崩溃。
我希望你们能帮助我,我已经找了一整天了。
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void readFile (float x[], int &y) {
ifstream load;
string filename;
cout << "Enter the name of the file: ";
cin >> filename;
load.open(filename.c_str());
while (!load.eof()) {
load >> x[y];
y++;
}
if (!load) {
cout << "asd";
}
}
void computeC (float x[], int y, float z[]) {
int v=0;
for (v=0; v<=y; v++) {
z[v] = (5 * (x[v] - 32)/9);
}
}
float average (float x[], int y) {
int v=0;
float sum=0;
for (v=0; v<=y; v++) {
sum += x[v];
}
return sum / v;
}
void grade (float x[], char grades[], int y, int &hi, int &med, int &lo) {
int v=0;
hi = med = lo = 0;
for (v=0; v<=y; v++) {
if ( x[v] >= 35) {
grades[v] = 'H';
hi++;
}
else if ( (x[v] < 35) && (x[v] >= 20) ) {
grades[v] = 'M';
med++;
}
else if ( x[v] < 20 ) {
grades[v] = 'L';
lo++;
}
}
}
void writeFile (float x[], float y[], int z, char w[]) {
ofstream save;
int v=0;
for (v=0; v <= z; v++) {
cout << "C(Celcius)" << left << setw(5);
cout << "F(Farenheit)" << left << setw(5);
cout << "Descriptionn";
cout << right << setw(7) << y[v];
cout << left << setw(8) << x[v];
cout << left << setw(8) << w[v];
}
}
int main(int argc, char** argv) {
int ctr=0, high, medium, low;
float F[ctr], C[ctr], ave;
char grades[ctr];
readFile (F, ctr);
computeC (F, ctr, C);
ave = average (C, ctr);
grade (C, grades, ctr, high, medium, low);
cout << "Average of the temperatures: " << ave << endl;
cout << "Number of high temperatures: " << high << endl;
cout << "Number of medium temperatures: " << medium << endl;
cout << "Number of low temperatures: " << low << endl;
//writeFile (F, C, ctr, grades);
return 0;
}
(来自 https://drive.google.com/file/d/0BxeZTCUL3Q4oZHlqWFdjMDZub0E/view?usp=sharing 的代码)
无需检查整个代码,我可以直接想到代码的某些部分。
让我从
while (!load.eof()) {
load >> x[y];
y++;
}
写入的值超过 x[] 可以容纳的值,在这种情况下,程序将崩溃。
确保只写入阵列,最多不超过最大分配的内存。
问题是 !load.eof() 不会做你期望它做的事情,因为它将从文件末尾之外读取。它会再次执行你的循环太多。
第二:
int ctr=0, high, medium, low;
float F[ctr], C[ctr], ave;
char grades[ctr];
ctr
0
,因此您声明了包含 0 个元素的 F, c and grades
数组。这不是很聪明;)您无法从中读取或写入。
相关文章:
- Visual Studio在尝试读取resource.txt文件时崩溃
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- For 循环在尝试读取数组 c++ 时程序崩溃
- Qt 5.9中的QML崩溃-帮助读取堆栈跟踪
- 使用向量的函数崩溃,调试器说访问冲突读取位置
- C 通过char读取文件字符串的文件char;崩溃
- 尝试从另一个过程读取32位整数时,ReadProcessMemory崩溃了
- 为什么我不能使用 ifstream 读取撇号而不会崩溃?
- 从CSV文件读取时,试图将值插入一个字符串中时崩溃
- c++ ifstream,从文件读取崩溃
- 程序使用SCANF读取字符串时会崩溃
- 简单的Logger类VSNPrintf正在随着读取访问违规行为而崩溃
- 程序使用FSCANF读取文件数据后崩溃
- 当我设置readdata并读取功能以上载文件时,libcurl会在fwrite()上崩溃
- 我的C++程序在尝试输出从文件中读取的数据时崩溃
- 读取空格会使解析器崩溃.为什么?
- 二进制树:从文件崩溃中读取
- C++程序在读取文本文件时崩溃
- C++程序崩溃中的文件读取错误
- 通过WinAPI套接字连接到蓝牙设备时崩溃(读取位置0x00000004时发生访问冲突)