Запуск исполняемого файла ничего не делает - PullRequest
0 голосов
/ 26 августа 2009

Я писал пример, включающий несколько файлов. Подробный код выглядит следующим образом.

main.cpp

#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include "grade.h"
#include "Student_Info.h"

using std::cin;
using std::cout;
using std::domain_error;
using std::endl;
using std::max;
using std::setprecision;
using std::sort;
using std::streamsize;
using std::string;
using std::vector;

int main()
{
    vector<Student_Info> students;
    Student_Info record;
    string::size_type maxlen = 0;       //the length of the longest name

    //read and store all the student's data
    //Invariant: students contains all the student records read so far
    //maxlen contains the length of the longest name in students
    while(read(cin,record))
    {
        //find length of the longest name
        maxlen=max(maxlen,record.name.size());
        students.push_back(record);
    }

    //alphabetize the student records
    sort(students.begin(),students.end(),compare);

    //write the names and grades
    for(vector<Student_Info>::size_type i=0; i!=students.size();++i)
    {
        //write the name, padded to the right to maxlen + 1 characters
        cout << students[i].name << string(maxlen+1-students[i].name.size(),' ');

        //compute and write the grade
        try
        {
            double final_grade=grade(students[i]);
            streamsize prec = cout.precision();
            cout << setprecision(3) << final_grade << setprecision(prec);
        }
        catch(domain_error e)
        {
            cout << e.what();
        }

        cout << endl;
    }

    return 0;
}

Student_info. {Ч, CPP}

#ifndef GUARD_Student_Info
#define GUARD_Student_Info

#include <iostream>
#include <string>
#include <vector>

using std::iostream;
using std::string;
using std::vector;

struct Student_Info
{
    std::string name;
    double midterm,final;
    std::vector<double> homework;
};

bool compare(const Student_Info&, const Student_Info&);
std::istream& read(std::istream&, Student_Info&);
std::istream& read_hw(std::istream&, std::vector<double>&);

#endif
#include "Student_Info.h"

using std::istream;
using std::vector;

bool compare(const Student_Info& x, const Student_Info& y)
{
    return x.name < y.name;
}

istream& read(istream& is, Student_Info& s)
{
    is >> s.name >> s.midterm >> s.final;

    read_hw(is,s.homework); //read and store all the students' homework grades
    return is;
}

istream& read_hw(istream& in, vector<double>& hw)
{
    if(in)
    {
        //get rid of previous contents
        hw.clear();

        //read homework grades
        double x;
        while(in>>x)
         hw.push_back(x);

        //clear the stream so that the input would work for the next student
        in.clear();
    }

    return in;
}

оценка. {Ч, CPP}

#ifndef GRADE_H
#define GRADE_H

//grade.h
#include <vector>
#include "Student_Info.h"

double grade(double,double,double);
double grade(double,double,const std::vector<double>&);
double grade(const Student_Info&);

#endif

#include <stdexcept>
#include <vector>

#include "median.h"
#include "grade.h"


double grade(const Student_Info& s)
{
    return grade(s.midterm,s.final,s.homework);
}

double grade(double midterm, double final, const vector<double>& hw)
{
    if(hw.size()==0)
        throw domain_error("student has done no homework");
    return grade(midterm, final, median(hw));
}

double grade(double midterm,double final,double homework)
{
    return 0.2*midterm + 0.4*final + 0.4*homework;
}

средний. {Ч, CPP}

#ifndef MEDIAN_H
#define MEDIAN_H

#include <vector>           
#include <stdexcept>        //to get the declaration of domain_error
#include <algorithm>        //to get the declaration of sortt

using std::domain_error;
using std::sort;
using std::vector;

double median(std::vector<double>);

#endif
#include "median.h"

double median(vector<double> vec)
{
    typedef vector<double>::size_type vec_sz;

    vec_sz size=vec.size();
    if(size==0)
        throw domain_error("median of an empty vector");
    sort(vec.begin(),vec.end());

    vec_sz mid=size/2;

    return size%2==0 ? (vec[mid]+vec[mid-1])/2:vec[mid];
}

Проблема в том, что когда я компилирую его с помощью g ++ в linux и запускаю ./a.out, ничего не происходит Это странно. Я перебрал код, но не смог найти ничего плохого. Надеюсь, кто-то может найти глюк.

Ответы [ 3 ]

6 голосов
/ 26 августа 2009

Под словом "ничего не происходит", вы имеете в виду, что он ожидает ввода и не выходит?

while(read(cin,record)) конечно, для меня это выглядит так. Передайте что-нибудь через стандартный ввод.

5 голосов
/ 26 августа 2009

Поиск ошибок путем визуального осмотра часто затруднен - ​​в нашем случае, в частности, потому что у нас все еще нет полного кода (несмотря на то, что вы опубликовали его значительную часть).

Вы должны научиться использовать gdb, отладчик GNU. Скомпилируйте вашу программу с помощью g++ -g, затем запустите gdb a.out. Затем я рекомендую следующие команды:

  • b main (устанавливает точку останова на main)
  • r (запускает программу, останавливается на главной)
  • s (пошаговая программа, чтобы вы могли понять, почему она ничего не делает)
2 голосов
/ 26 августа 2009

Вы предоставляете информацию? Эта программа ожидает чтения серии записей Student_Info из стандартного ввода. Если у вас есть файл, содержащий записи учеников, вам понадобится командная строка, например:

./a.out < student_records.txt
...