2013-05-04 106 views
0

我正在嘗試讀取具有多列的文件,以輸出收入超過$ 100,000和GPA小於或等於2.3的所有結果。我無法弄清楚哪種方法是正確的。文件輸出甚至不出現在終端上。請讓我知道是否需要更多細節。這裏是FILEC++簡單多列文件讀取

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 

ifstream inputFile; 
char *student = new char[]; 
int salary=100000, 
    grades=2.3; 

inputFile.open("Students.txt"); 

if(inputFile.fail()==1) 
    { 
    cout<<"File opening failed"; 
    } 
    else 
     { 
      while(!inputFile.eof()) 
      { 
       inputFile>>student; 
      } 

      inputFile.close(); 
     } 

int income=student[0]; 
int gpa=student[0]; 


    for(int i=0;i!=inputFile.eof();i++) 
    { 
     income=student[i]; 
     gpa=student[i]; 

     if(income>=salary && gpa<=grades) 
     { 
      cout<<" "<<income<<" "<<gpa<<endl; 
     } 
    } 


cin.get(); 
cin.get(); 

return 0; 
} 
+0

首先,'字符*學生=新的char []'沒有意義 - 你需要在括號內指定的大小。 – 2013-05-04 01:52:54

+0

啊,他是從.... J/K總裁 http://stackoverflow.com/questions/8723224/using-sscanf-to-parse-a-string – 2013-05-04 01:55:35

+2

你覺得這樣做? 'for(int i = 0; i!= inputFile.eof(); i ++) '?提示:這是無意義的(但會編譯)。 – 2013-05-04 01:55:51

回答

0
#include <fstream> 
#include <iostream> 

const int MAX_STUDENTS = 100; 

int main() 
{ 
int numberOfStudents = 0; 

//Instantiate read file object 
std::ifstream inputFile("Student.txt"); 

//Instantiate an array of income 
int income[MAX_STUDENTS]; 
float gpa[MAX_STUDENTS]; 

//Check if the file is open 
if(inputFile.fail() == 1) 
    std::cout << "\nFile opening failed!\n"; 
else 
{ 
    while(!inputFile.eof()) 
    { 
     //Read file into class 
     inputFile >> income[numberOfStudents]; 
     inputFile >> gpa[numberOfStudents]; 

     //^^**In whatever order your data members are in** 

     //Check if gpa and income meet requirements 
     if(income[numberOfStudents] > 100000 && gpa[numberOfStudents] <= 2.3) 
     { 
      /*Output student if gpa is less than or equal to 2.3 AND 
      greater than 100000*/ 
      std::cout << "\nStudent #: " << numberOfStudents + 1 << ' ' << std::endl; 
      std::cout << income[numberOfStudents] << ' '; 
      std::cout << gpa[numberOfStudents] << ' '; 
      std::cout << ' ' << std::endl; 
     } 
     //Increase number of students 
     numberOfStudents++; 
    } 
    //Close file 
    inputFile.close(); 
} 
return 0; 

}

+0

沒有類沒有更直接的方法嗎?我繼續得到課堂類型錯誤。 – Klinetel 2013-05-04 03:15:45

+0

你可以用結構來實現。你得到什麼錯誤?您需要修改代碼以確保它正確讀入文本文件。 – MrPickle5 2013-05-04 03:24:25

+0

現在我得到的標識符是未定義的,>>沒有操作符匹配這些操作數。 – Klinetel 2013-05-04 03:28:26