【发布时间】:2014-12-02 08:36:15
【问题描述】:
首先,我想让你知道我是一名大学生(我们的编程课程还没有那么高级)(顺便说一句,我没有要求我的作业等答案,我只是在练习)。
好的,我有两个问题
- 我的代码中的某些函数改变了我的数组的值(当我不想要它时)
- 我真的不知道,但似乎从文件中获取一些值以存储到我的数组中会使程序崩溃,此外,在稍微修改一下代码之后(我不知道发生了什么变化),它不再崩溃在上述部分中,但它仍然在代码执行结束时崩溃..
我希望你们能帮助我,我整天都在寻找。
#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 << "Description\n";
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的代码)
【问题讨论】:
-
欢迎来到 SO。如果您想获得帮助,您的问题可能会有所改进。尝试阅读以下内容:stackoverflow.com/help/how-to-ask 告诉我们究竟是什么不起作用。
-
欢迎来到 stackoverflow.com。请花一些时间阅读the help pages,尤其是名为"What topics can I ask about here?" 和"What types of questions should I avoid asking?" 的部分。也请read about how to ask good questions。您可能还想了解如何创建Minimal, Complete, and Verifiable example。
-
至于你的问题,首先不要做例如
while (!load.eof())因为它不会像您期望的那样工作。eofbit标志在您尝试从文件末尾之外读取之前不会设置,因此您的循环将迭代一次到多次。其次,在您的main函数中,您声明数组F和C具有零大小!这意味着对它们的每次访问(读取或写入)都将越界导致undefined behavior。 -
你也应该知道 txtspk 是不受欢迎的。