开发者

reading information from a text file into 3 different arrays from a text file (c++)

I'm having trouble with this program from c++ class: A teacher has created parallel arrays of students with last names, first names and test scores. The arrays are arranged such that the nth element of each array contains the related information. Write a program that sorts (using a selection sort) the arrays by the students last name, so that the nth term of each array still contains the data related to the correct person. for example the original array data is as follows:

Ratte Ismella 66

Brown Tom 88

Dyrt Phil 94

Dent Stu 100

After sorting:

Brown Tom 88

Dent Stu 100

Dyrt Phil 94

Ratte Ismella 66

The program must work for up to 30 students. Data must be read from a data file. each line of the data file will contain a last name, a space, first name, a space, and integer score. The program must display 开发者_JAVA技巧the data before and after sorting.

I know I'm supposed to include a selection sort and swap function, but I'm not sure how to do that. here is what I have so far its not very good

#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void selsort(int a[], int size)
void swap(string, &s1,string &s2)
void swap (int &i1, int &i2)

int main()
{
    int counter=0;
    ifstream inputFile;
    string inputFileName;
    cout<<"Enter the path and filename.";
    getline(cin, inputFileName);
    inputFile.open (inputFileName.c_str());
    string LINE;
    while (!inputFile.eof())
    {
        getline (inputFile, LINE)
        cout<<LINE<<endl;
    }

I know i'm supposed to read the file in as words not lines, I do not know how to put them into arrays based on last name first name, and score, and the variables used in my selsort and swap declarations are all wrong, and lastly I'm supposed to use only 1 dimensional arrays.


You seem to have have multiple questions regarding your homework assignment.

Q1: How do I store my data?

First, you need to declare the arrays. In C++, an array is a fundamental data structure of fixed size that represents an homogeneous set of data. An array is characterized by its type and its size. If T represents some arbitrary type, and N represents some arbitrary constant expression, you can declare an array named myArray thus: T myArray[N]. Specifically, you could declare these three arrays

std::string LastNames[30];
std::string FirstNames[30];
int Scores[30];

When accessing the elements of these arrays, we use the subscript operator [] e.g.,

LastName[7] = "Johnson";
std::cout << Scores[23]; 

Q2: How do I read in my data?

To populate these arrays, we use the insertion operator from std::istream : >>. This operator reads a white-space-delimited word from its input stream, interprets it appropriately, and assigns that value to the named variable. For example, to read in a single int, we might write:

int i;
std::cin >> i;

Reading in value after value, until the end of file is reached, is a common C++ idiom. In the case of repeatedly reading in one type of data, we use a form like this:

std::string name;
while(std::cin >> name) {
    // do something with "name"
}

In this particular case, we use a feature called "operator chaining" to read three values in for each loop iteration:

std::string lastName;
std::string firstName;
int score;
while(std::cin >> lastName >> firstName >> score) {
}

This loop runs several times, until the end of file is reached. Each iteration of the loop assigns the next set of values to these named variables. Note that this loop is silly, because we don't do anything with the values. We immediately overwrite them with the next iteration.

Combining the array concept with the reading-input idiom, we have:

std::string LastNames[30];
std::string FirstNames[30];
int Scores[30];
std::string lastName;
std::string firstName;
int score;
int i = 0;
while(std::cin >> lastName >> firstName >> score) {
    LastNames[i] = lastName;
    FirstNames[i] = firstName;
    Scores[i] = score;
    ++i;
}
int NumberOfStudents = i;

Q3: How do I sort my data?

I won't write your selsort algorithm for you, but you'll probably have something like:

for(int i = 0; i < NumberOfStudents; i++) {
    for(j = i; j < NumberOfStudents; j++) {
        // do some compares
        // swap some data
    }
}

In a typical sort, the "do some compares" and "swap some data" lines will operate on the same data structures. So, if your compare line is like if (data[i] < data[j]), then your swap line would look like std::swap(data[i], data[j]).

Your data structures are not typical, however. You have three parallel arrays, which must be sorted as a single set, not as three distinct sets. In your case, your "do some compares" line might be if (LastNames[i] < LastNames[j]), but your swap lines will have to do identical swaps in all three arrays:

std::swap(LastNames[i], LastNames[j])
std::swap(FirstNames[i], FirstNames[j])
std::swap(Scores[i], Scores[j])      

By the way, this extra complication is one excellent reason why you should never use parallel arrays -- they make you repeat yourself, increasing the opportunity for error.

I hope that this answer allows you to complete your homework on your own, without showing you too much of how to do it. Don't forget to upvote each answer you found helpful, and to accept the answer (if any) which solved your problem.


Something like:

vector <string> firstname, lastname;
vector <int> score;
string fn, ln;
int n;

while( inputfile >> fn >> ln >> n ) {
     firstname.push_back( fn );
     lastname.push_back( ln );
     score.push_back( n );
}

Under no circumstances use the eof() member function until you understand what it actually does - hint: it does NOT predict if the next read will cause an end of file.


I wont write the code for this (HW que) , but still give you general idea of doing it in c++.

1) Data structure for each student.

struct stud{
std::string last;
std::string first;
int number
};

2. tokenize the line you get for spaces or do as unappersson has suggested.

your container will be :: vector < stud * > students; [DO NOT FORGET TO DELETE THE POINTERS]

3 . Access last name as :: students[iterator] -> last and do Selection sort on strings.

vector < stud * > ::iterator it;
for(it = students.begin() ; it != students.end() ; it++){
// This is the way to iterate through your students container
}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜