Need help(won't read the array)

Hello, So this is part of my homework. I have been stuck on this code for hours now. I feel like I've tried everything or that I am just missing something super simple. Every time I run the code it only shows white space. I'm not sure where I have gone wrong. I've tried error checking parts of the code, but I can't figure it out. Please help.

I feel like I messed up somewhere. The second part is me just trying to check what is going wrong but I can't find it.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
#include<string>
#include<fstream>
#include <algorithm>

using namespace std;

int main ()
{

    ifstream inputfile;
    string filename;
    const int numstudents = 25;
    string name[numstudents];
    int y = 0;

//get filename
    cout << "Hello, Please enter the file name you would like to use. " << endl;
    cin >> filename;
// open file name
    inputfile.open(filename.c_str());

// read filename into array
    if(inputfile)
    {
        while(true)
        {
            inputfile >> name[y];
            y++;

            if(inputfile.eof())
                break;
        }

       
    }
//sort and output in alphabetical order.
        for(int i=0; i< numstudents; i++)

        cout << "Here are all the students names in alphabetical order: " << endl;
        sort(name, name + numstudents);

        for (int i = 0; i < numstudents; i++)
        {
            cout << name[i] << endl;

        }








    return 0;
}





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

using namespace std;

int main ()
{

    ifstream inputfile;
    string filename;
    const int numstudents = 25;
    string name[numstudents];



    cout << "Hello, Please enter the file name you would like to use. " << endl;
    cin >> filename;

    inputfile.open(filename.c_str());
    int y = 0;
    if(inputfile)
    {
        while(true)
        {
            inputfile >> name[y];
            y++;

            cout << name[y] << endl;

            if(inputfile.eof())
                break;
        }


    }


    return 0;
}

Last edited on
Please post a sample of your input file.

Since you're trying to sort your whole array when you probably only have a few entries is probably part of the problem. You should only be sorting for the actual number of elements retrieved from the file, not the whole array.

By the way your input loop is probably incorrect, it should probably be more like:

1
2
3
4
5
6
7
8
    if(inputfile)
    {
        while(y < numstudents && input >> name[y])
        {
            y++;
        }

    }


Oh and what happens if the input file fails to open?

fixed it myself finally!!!!!!!
Topic archived. No new replies allowed.