C++函数不会调用最后一个参数



我有一项作业,我必须展示大学书店的主题、成本、总额和最便宜的课本。我必须从输入文件中读取数据,并通过各种函数传递参数来完成这项工作。我已经设法通过并显示了前4门科目,但最后一门,数学,不会从输入文件中读取,也不会显示。我得到的错误是:"调试断言失败"。我已经附上了完整的错误和程序的输出。下面是我的代码。感谢任何帮助或提示,因为我已经想了几个小时了。谢谢

输出和错误

enter code here
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
void print_output(int text_num, double t1, double t2, double t3, double tot, 
int num, double cheap_one);
using namespace std;
int main() {
string  store_name;
string subject;
// define variables
ifstream inData;
ofstream outData;
string Biology, Chemistry, English, Computer, Mathematics;
double text1, text2, text3;
double total1;
double small;
double text_num = 1;
double num = 1;
cout << fixed << showpoint << setprecision(2);
// print titles here like dereks bookstore and the subjects plus 
text/cheapest 
cout << "Derek's Bookstore" << endl;
cout << endl;
cout << "Subjectt" << setw(5) << "    Text 1t" << "Text 2t" << "Text 3t" 
<< "Totalt" <<
"    Cheapest/Amountt" << endl;
cout << endl;
inData.open("first_project_data.txt");
if (!inData) {
cout << "nCannot open input file." << endl;
system("PAUSE");
return 0;
}
inData >> subject;
while (inData) {
//cout << "nn**at beginning" << subject << endl << endl;
inData >> text1 >> text2 >> text3;
// calculate totals
total1 = text1 + text2 + text3;
// find out the cheapest book (use if statement )
small = text1;
if (text1 > text2)
small = text2;
if (small > text3)
small = text3;
// call the print function
//cout << text1 << " Before print" << total1;
//system("PAUSE");
print_output(text_num, text1, text2, text3, total1, num, small);
text_num++;
inData >> subject;
}

//cout << "nn**at end" << subject << endl << endl;

// output the last total line
inData.close();
outData.close();
system("PAUSE");
return 0;
}
void print_output(int subject, double t1, double t2, double t3, double 
tot, int num, double cheap_one) {
char text_name[8], subject_name[10];
switch (subject) {
case 1: strcpy_s(subject_name, "Biology");
break;
case 2: strcpy_s(subject_name, "Chemistry");
break;
case 3: strcpy_s(subject_name, "English");
break;
case 4: strcpy_s(subject_name, "Computer");
break;
case 5: strcpy_s(subject_name, "Mathematics");
break;
}
switch (num) {

case 1: strcpy_s(text_name, "text1");
break;
case 2: strcpy_s(text_name, "text2");
break;
case 3: strcpy_s(text_name, "text3");
break;
}
cout << setw(12) << left << subject_name << t1 << "t" << t2 << "t" << t3 
<< "t" << tot << "tt"
<< text_name << "/$ " << cheap_one << endl;
}

您的char数组subject_name有10个字符长,但"Mathematics"需要12个字符(包括training null(。

strcpy_s检测到这种情况,并将其报告为您看到的断言。因此,这个函数比未检查的strcpy更可取,后者只会无声地产生缓冲区溢出,如果幸运的话,这可能会导致我们的程序崩溃或出现安全漏洞。

我建议使用std::string,而不是处理char数组大小。

最新更新