C ++简单多列文件读取

时间:2013-05-04 01:39:14

标签: c++ arrays visual-c++ file-io

我正在尝试读取包含多列的文件,以输出收入超过100,000美元且GPA小于或等于2.3的所有结果。我无法弄清楚哪种方法是正确的。文件输出甚至不会出现在终端上。如果需要更多细节,请告诉我。这是FILE

#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;
 }

1 个答案:

答案 0 :(得分: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;

}