2015-06-04 2 views
-1

Мое задание о массивах и структурах. Первая часть, которую мне нужно сделать, - это прочитать данные из входного файла. Тем не менее, я застрял на этом. Я знаю, что у меня есть некоторые случайные числа. Однако я не могу найти его. Мне потребовался час, чтобы найти эти ошибки. Можете ли вы, ребята, показать мне, где я ошибся? Я буду признателен. Спасибо!!!Я не получаю нужные данные. Я просто получил случайное число

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

const int SIZE=15; 

// Here is my structure declaration. 
struct BestColleges 
{ 
    int rnk;  // The rank of college. 
    string name; //The college name. 
    int years;  // Which years did college establish? 
    string email; // The address of college. 
    double TranferRate; // % of students who graduate and transfer 
    double RetentionRate; // % of students who first year retention. 
    int low_cost;  // The lower cost of attendance 
    int high_cost;  // The higher cose of attendance 
    double numStudents; // how many students in the college. 
}; 

void getData (BestColleges c[], BestColleges *plast); 
void printCollege1 (BestColleges College[],BestColleges *plast); 

int main() 
{ 
    ifstream inputFile; 
    int num_college; 

    cout << " Welcome to my program!!! " << endl; 

    BestColleges *College; 
    College = new BestColleges[SIZE]; 
    BestColleges *ptr; 
    BestColleges *plast = College+ SIZE-1; 
    ptr= College; 

// Here is my function definition 
    getData(College, plast); 
    printCollege1(College, plast); 


    // I'm testing if I got the data from input file 
//cout << num_college << endl; 



    cout << " Thank you for reading my program! See you again!" << endl; 

    return 0; 
} 
// Here is my fuction definition 
void getData (BestColleges c[], BestColleges *plast) 
{ 
    ifstream inputFile; 
    int num_college; 

    inputFile.open("CA_BestColleges.txt"); 
    inputFile >> num_college; 

    for (BestColleges *p =c; p < plast; p++) 
     { 
      inputFile >> p->rnk; 
      getline(inputFile,p->name); 
      inputFile >> p->years; 
      getline(inputFile,p->email); 
      inputFile >> p->TranferRate; 
      inputFile >> p->low_cost; 
      inputFile >> p->high_cost; 
      inputFile >> p->numStudents; 

     } 
     inputFile.close(); 
} 
void printCollege1 (BestColleges c[],BestColleges *plast) 
{ 

    for (BestColleges *ptr = c; ptr < plast; ptr++) // Here is my printing entirely information. 
      { 
       cout << " Rank: " << ptr->rnk << endl; 
       cout << " Name: " << ptr->name << endl; 
       cout << " Email: " << ptr->email << endl; 
       cout << " Graduation and Transfer Rate: " << ptr->TranferRate << endl; 
       cout << " First Year Retention Rate: " << ptr->RetentionRate << endl; 
       cout << " Cost of Attendance: " << "$" << ptr->low_cost << " - " << "$" << ptr->high_cost << endl; 
       cout << " Number of Students: " << " approx. " << ptr->numStudents << endl; 
       cout << endl; 
      } 
} 

Вот мой входной файл:

15 
Palo Verde College 
1947 
http://www.paloverde.edu 
31.2 82.7 14266 18266 3898 
4 
Diablo Valley College 
1949 
http://www.dvc.edu 
50.2 90.5 14839 20579 24781 
6 
Foothill College 
1957 
http://www.foothill.edu 
68.8 87.5 12300 19302 18362 
12 
College of the Siskiyous 
1957 
http://www.siskiyous.edu 
59.8 82.0 15306 21936 2473 
10 
Cuesta College 
1963 
http://www.cuesta.edu 
50.7 86.2 12052 19135 9571 
8 
Ohlone College 
1965 
http://www.ohlone.edu 
52.1 91.1 10898 15878 18000 
+0

Можете привести пример входного файла? – meneldal

+0

Как вы разбираете текстовый файл? Кстати, здесь не место задавать вопросы о назначении, но я бы порекомендовал вам задать конкретную информацию по заданному вопросу, который может помочь вам в работе над вашим заданием. – macroland

+0

Я имею в виду, я знаю, что у меня есть номер мусора. Однако я не знаю, где я ошибся. Я просто хочу спросить, где это. Я не хочу, чтобы ты исправил это для меня. ищут его –

ответ

0

Вы получаете плохие результаты, потому что вы не правильно разбор:

for (BestColleges *p =c; p < plast; p++) 
    { 
     inputFile >> p->rnk; 
     getline(inputFile,p->name); 
     inputFile >> p->years; 
     getline(inputFile,p->email); 
     inputFile >> p->TranferRate; 
     inputFile >> p->low_cost; 
     inputFile >> p->high_cost; 
     inputFile >> p->numStudents; 

    } 

Вы упускаете inputFile >> p->RetentionRate;. Из-за этого следующие пункты будут считывать неожиданные данные и будут приводить к плохим результатам.

0

У вас есть разовое чтение для количества колледжей, но оно не находится в файле, поэтому в него считывается ранг. После этого остальная часть синхронизации.

Смежные вопросы