?
Solved

Read file into an array using struct and print to screen

Posted on 2007-10-03
13
Medium Priority
?
481 Views
Last Modified: 2010-04-01
Hi,
I am just getting started on a program for  an assignment, and am having some trouble. I am trying to read a file that I created into an array that contains first name, last name, a test score, and a letter grade (may have a + or - with the letter). I woulfd then like to print out the data from the file to the screen. While I have to do more than this before it is finished, I thought that getting this working would be a good start. There will be exactly 10 records in the file.
Any assistance would be appreciated. I am just a beginner.

The input file

Jon                 Schab               96 A
David              Jones               94 A-
Paul                Stevens            88 B+
Sam                Waters             77 C+
Mike                Smith                89 D+
Joseph            Mantas            84 B
Mary                Sheth              80 B-
Susan              Smith              98 A
Terry               Bradshaw       89 B+
Dan                 Marino              75 C  

The non-compilable program

#include <iostream>
#include <cstdlib>
#include <fstream>


using namespace std;



struct studentType
{
    string studentFName[20];
    string studentLName[20];
      int testScore;
      string grade[2];

};


void readfile()

{
          char filename[]= "students.txt";
       
        infile.open(filename);

        if (infile.fail())
        {
                cout << "File doesn't exist" << endl;
                exit(0);
        }

        infile.close();
}

void main()
{
    StudentType student[10];
      readfile();




    cout << "First name, Last name, Score, Grade" << endl;
    for (i=0;i<10;i++)
    {
        cout << student[i].studentFName << " ";
        cout << studentLName[i].studentLName  << " ";
        cout << student[i].testScore        << " ";
        cout << student[i].grade        << " ";
    }

}
     
0
Comment
Question by:ghost8067
  • 6
  • 4
  • 3
13 Comments
 
LVL 53

Expert Comment

by:Infinity08
ID: 20006386
Can you show the errors you get ? You have to solve them one at a time (usually they explain pretty well what the problem is).

A few things that I see already :

1) You have to be consistent in your use of uppercase and lowercase. StudentType is not the same as studentType.

2) readfile does not have access to the student array in main, so it can't write the results in there. You could pass the student array as an argument to the readfile function.

3) the readfile function does not do anything yet ... but I'm sure you know that ;)

4) the main should return an int, not void !!

5) you're using the STL string, so you need to add #include <string> at the top of the source code.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 20006399
and one more :

6) if you use a string, then you don't have to specify the length between [] ... you can just leave that out.
0
 

Author Comment

by:ghost8067
ID: 20006805
I made a coupel of the changes. Since I just want to print to get myself started and verify the read, I moved the print to the read function. I also made the change to studentType and got rid of the {} for the strings. The new code is below followed by the errors.

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


using namespace std;



struct studentType
{
    string studentFName;
    string studentLName;
      int testScore;
      string grade;

};


void readfile()

{
          char filename[]= "students.txt";
       
        infile.open(filename);

        if (infile.fail())
        {
                cout << "File doesn't exist" << endl;
                exit(0);
        }
    cout << "First name, Last name, Score, Grade" << endl;
    for (i=0;i<10;i++)
    {
        cout << student[i].studentFName << " ";
        cout << studentLName[i].studentLName  << " ";
        cout << student[i].testScore        << " ";
        cout << student[i].grade        << " ";
    }
        infile.close();
}

void main()
{
    studentType student[10];
      readfile();
}

Errors
Wk4_Ex01.cpp(26): error C2228: left of '.open' must have class/struct/union type type is ''unknown-type''
Wk4_Ex01.cpp(26): error C2065: 'infile' : undeclared identifier
Wk4_Ex01.cpp(28): error C2228: left of '.fail' must have class/struct/union type ttype is ''unknown-type''
Wk4_Ex01.cpp(28): error C3861: 'infile': identifier not found, even with argument-dependent lookup
Wk4_Ex01.cpp(34): error C2065: 'i' : undeclared identifier
Wk4_Ex01.cpp(34): error C3861: 'i': identifier not found, even with argument-dependent lookup
Wk4_Ex01.cpp(34): error C3861: 'i': identifier not found, even with argument-dependent lookup
Wk4_Ex01.cpp(36): error C2065: 'student' : undeclared identifier
\Wk4_Ex01.cpp(36): error C2228: left of '.studentFName' must have class/struct/union typeWk4_Ex01.cpp(36): error C3861: 'i': identifier not found, even with argument-dependent lookup
Wk4_Ex01.cpp(37): error C2065: 'studentLName' : undeclared identifier
Wk4_Ex01.cpp(37): error C2228: left of '.studentLName' must have class/struct/union type
Wk4_Ex01.cpp(37): error C3861: 'i': identifier not found, even with argument-dependent lookup
Wk4_Ex01.cpp(38): error C2228: left of '.testScore' must have class/struct/union type
Wk4_Ex01.cpp(38): error C3861: 'student': identifier not found, even with argument-dependent lookup
Wk4_Ex01.cpp(41): error C2228: left of '.close' must have class/struct/union type
        type is ''unknown-type''
Wk4_Ex01.cpp(41): error C3861: 'infile': identifier not found, even with argument-dependent lookup


 
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:ghost8067
ID: 20007021
I tried to add reading the data in. The newest version is below followed by the errors.

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


using namespace std;



struct studentType
{
    string studentFName;
    string studentLName;
      int testScore;
      string grade;

};


void readfile()
int i;
{
          char filename[]= "students.txt";
       
        infile.open(filename);

        if (infile.fail())
        {
                cout << "File doesn't exist" << endl;
                exit(0);
        }
      
      //get the data
    for (i=0; i<10; ++i) {
    student[i] = studentType(student[i]);
    }

    cout << "First name, Last name, Score, Grade" << endl;
    for (i=0;i<10;i++)
            int i;
    {
        cout << student[i].studentFName << " ";
        cout << studentLName[i].studentLName  << " ";
        cout << student[i].testScore        << " ";
        cout << student[i].grade        << " ";
    }
        infile.close();
}

void main()
{
    studentType student[10];
      readfile();

}

Errors

Wk4_Ex01.cpp(22): error C2501: 'i' : missing storage-class or type specifiers
Wk4_Ex01.cpp(22): warning C4518: 'int ' : storage-class or type specifier(s) unexpected here; ignored
Wk4_Ex01.cpp(22): error C2146: syntax error : missing ';' before identifier 'i'
Wk4_Ex01.cpp(23): error C2447: '{' : missing function header (old-style formal list?)
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 20007046
>> Wk4_Ex01.cpp(26): error C2228: left of '.open' must have class/struct/union type type is ''unknown-type''

You're using infile without declaring it. It needs to be an ifstream :

        http://www.cplusplus.com/reference/iostream/ifstream/open.html

A lot of the other errors are because of this.


>> Wk4_Ex01.cpp(34): error C2065: 'i' : undeclared identifier

You're using i without declaring it. You can change this :

        for (i = 0; i < 10; ++i)

to :

        for (int i = 0; i < 10; ++i)


>> Wk4_Ex01.cpp(36): error C2065: 'student' : undeclared identifier

As I said in my earlier post, the readfile function does not have access to the student declared in main. You need to pass it as a parameter to the function. Take a look at this tutorial on functions :

        http://www.cplusplus.com/doc/tutorial/functions.html
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 20007057
btw :

>> 4) the main should return an int, not void !!

Change the return type of main to int instead of void, and add this line at the end of main :

        return 0;
0
 
LVL 86

Expert Comment

by:jkr
ID: 20007616
>>Wk4_Ex01.cpp(22): error C2501: 'i' : missing storage-class or type specifiers

Instead of

void readfile()
int i;
{

that should be

void readfile()
{
int i;


Also, you are missing the declaration of

ifstream infile;
0
 

Author Comment

by:ghost8067
ID: 20009845
I have made a few of the changes. I am still having trouble figuring out passing the data structure into the function. Can anyone provide some insight?

The updated code is below.

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


using namespace std;



struct studentType
{
    string studentFName;
    string studentLName;
      int testScore;
      string grade;

};


void readfile(string a)
{
            string student = a;
            
            fstream infile;

            char filename[]= "students.txt";
       
        infile.open(filename);

        if (infile.fail())
        {
                cout << "File doesn't exist" << endl;
                exit(0);
        }
      
      //get the data
    for (int i=0; i<10; ++i) {
    student[i] = studentType[i];
    }

    cout << "First name, Last name, Score, Grade" << endl;
    for (int i=0;i<10;i++)
      {
        cout << student[i].studentFName << " ";
        cout << student[i].studentLName  << " ";
        cout << student[i].testScore        << " ";
        cout << student[i].grade        << " ";
    }
        infile.close();
}

int main()
{
    studentType student[10];
      readfile(studentType);

}

Errors I am getting

wk4_ex01.cpp(39) : error C2275: 'studentType' : illegal use of this type as an expression
wk4_ex01\wk4_ex01.cpp(12) : see declaration of 'studentType'
wk4_ex01.cpp(45) : error C2228: left of '.studentFName' must have class/struct/union
        type is 'char'
wk4_ex01.cpp(46) : error C2228: left of '.studentLName' must have class/struct/union
        type is 'char'
wk4_ex01.cpp(47) : error C2228: left of '.testScore' must have class/struct/union
        type is 'char'
wk4_ex01.cpp(48) : error C2228: left of '.grade' must have class/struct/union
        type is 'char'
wk4_ex01.cpp(56) : error C2275: 'studentType' : illegal use of this type as an expression
        c:\documents and settings\administrator\my documents\visual studio 2005\projects\wk4_ex01\wk4_ex01\wk4_ex01.cpp(12) : see declaration of 'studentType'
0
 
LVL 86

Accepted Solution

by:
jkr earned 1000 total points
ID: 20009874
Well, that should be

    studentType student[10];
      readfile(student); // pass the array, not the type name

and

void readfile(studentType* student)
{

0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 1000 total points
ID: 20009882
>> wk4_ex01.cpp(39) : error C2275: 'studentType' : illegal use of this type as an expression

studentType is the type, and student is an array of elements of that type. When you pass a variable to a function, you need to pass an instance of the type, not the type itself.

So, the function call becomes :

      readfile(student);

instead of :

      readfile(studentType);

and the function header becomes :

      void readfile(studentType student[10])

instead of :

      void readfile(string a)

as we want to take a studentType array as argument, and not a string. Note that now you can use the student array inside the function, so you'll have to modify the function logic to use that array. I'll let you give that a try ... post here if you have problems with that.


Also, it's a good idea to make infile an ifstream instead of an fstream (we only want it for input).
0
 

Author Comment

by:ghost8067
ID: 20010669
I put together the load of the array and have it working fine. The file now opens and diplays. Thanks for the help on that. I have posted my updated code below. I was wondering if you could answer one more question before I close the thread. I have to do the following now:

 A function to assign the relevant grade to each student. (Calculate the grade)
 A function to find the highest test score.
 A function to print the names of the students having the highest test score.

I have to do it with only function calls in main. So, can you tell me if there is a way to pass back the filled array, and then how I would pass it to another function?

Thanks!

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


using namespace std;



struct studentType
{
    string studentFName;
    string studentLName;
      int testScore;
      string grade;
};


void readfile(studentType student[10])
{
            int x = 0;
              ifstream infile;

            char filename[]= "students.txt";
       
        infile.open(filename);

        if (infile.fail())
        {
                cout << "File doesn't exist" << endl;
                exit(0);
        }

     while( infile && x < 10 )
     {
       infile >> student[x].studentFName >> student[x].studentLName >> student[x].testScore >> student[x].grade;
       x++;
       }
     
    cout << "First name, Last name, Score, Grade" << endl;
    for (int i=0;i<10;i++)
            {
        cout << student[i].studentFName << " ";
        cout << student[i].studentLName  << " ";
        cout << student[i].testScore        << " ";
        cout << student[i].grade        << " " << endl;
            }
        infile.close();
}


int main()
{
    studentType student[10];
      readfile(student);

}

0
 
LVL 86

Expert Comment

by:jkr
ID: 20011364
>>So, can you tell me if there is a way to pass back the filled array, and then
>>how I would pass it to another function?

Just use e.g.

void printfile(studentType* student)
{
    for (int i=0;i<10;i++)
            {
        cout << student[i].studentFName << " ";
        cout << student[i].studentLName  << " ";
        cout << student[i].testScore        << " ";
        cout << student[i].grade        << " " << endl;
            }

int main()
{
    studentType student[10];
      readfile(student);
      printfile(student);

}
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 20012300
>> I have to do it with only function calls in main. So, can you tell me if there is a way to pass back the filled array, and then how I would pass it to another function?

The readfile function already uses the array in the main (because you passed it as a parameter). So, the data that you read in the readfile function is also available in main. All you have to do is create a few more functions that take that array as parameter, and call them from main (just like jkr showed).


For example, try moving this loop to the main (after the readfile call) :

    cout << "First name, Last name, Score, Grade" << endl;
    for (int i=0;i<10;i++)
            {
        cout << student[i].studentFName << " ";
        cout << student[i].studentLName  << " ";
        cout << student[i].testScore        << " ";
        cout << student[i].grade        << " " << endl;
            }

and see what happens ;)
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question