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

时间:2018-12-06 19:59:58

标签: c++ function parameters

我有一个作业,必须显示大学书店的主题,费用,总和最便宜的教科书。我必须从输入文件中读取数据,并通过各种功能传递参数以完成此操作。我设法使前四个主题通过并显示,但是最后一个主题,数学,不会从输入文件中读取,也不会显示。我得到的错误是:“调试断言失败”。我已经附上了完整的错误和程序的输出。下面是我的代码。感谢您的帮助或提示,因为我已经尝试解决了几个小时。谢谢。

The output and error

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 << "Subject\t" << setw(5) << "    Text 1\t" << "Text 2\t" << "Text 3\t" 
<< "Total\t" <<
    "    Cheapest/Amount\t" << 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 << "\n\n**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 << "\n\n**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 << "\t\t"
    << text_name << "/$ " << cheap_one << endl;

}

1 个答案:

答案 0 :(得分:5)

您的字符数组subject_name的长度为10个字符,但是“数学”需要12个字符(包括训练空值)。

strcpy_s检测到这种情况并将其报告为您看到的断言。因此,与未经检查的strcpy相比,此功能更可取,后者会以静默方式产生缓冲区溢出,如果您幸运或存在安全漏洞,可能会使我们的程序崩溃。

建议不要使用char数组大小,而建议使用std :: string。