How do i read the contents into an integer array from my file?

Hello, i'm pretty new to programming and know how to use arrays a little bit, but now i'm trying to add an array with 200 numbers from my text file. i Keep getting errors when doing so, any help and a brief explanation would be greatly appreciated. I'm not really sure what to do with the commented bottom code as well. But my file does open with all the numbers.

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
  #include <iostream>
#include <fstream>
#include <string>

using namespace std;

int binarySearch(int array[], int size, int value);
void selectionSort(int array[], int size);
const int SIZE = 200;
int numbers[SIZE];
int count;


int main()
{

    // prompt user to enter file name. also display if it exists or not
    ifstream inputFile; // gives access to file
    string name, filename;
    int number;

    // Get file name from the user
    cout << "Enter the file name: ";
    cin >> filename;

    // Open the file
    inputFile.open(filename.c_str());

    // If the file opened successfully, process it
    if (inputFile)
    {
        // Read the numbers from the file and display them.
        while (inputFile >> number)
        {
            cout << number << endl;
        }

        // Close the file
        inputFile.close();
    }
    else
    {
        // display an error message if the file was not found
        cout << "Error opening the file.\n";
    }
   return 0;
}
    // read contents into integer array


      for (count = 0); count < number; count++ ///// This Spot????




    // sort the array using selection sort
 void selectionSort(int array[], int size){

       int startScan, minIndex, minValue;

       for (startScan = 0; startScan < (size - 1); startScan++)
       {
            minIndex = startScan;
            minValue = array[startScan];
            for(int index = startScan + 1; index < size; index++)
            {
                if (array[index] < minValue)
                {
                    minValue = array[index];
                    minIndex = index;
                }
            }
            array[minIndex] = array[startScan];
            array[startScan] = minValue;
       }
}

    // prompt the user to enter a # to search the array or Q to quit




    // perform a binary search to locate the number, If found display
    int binarySearch(int array[], int size, int value)
{

        int first = 0, // First array element
        last = size - 1, // Last array element
        middle, // Mid point of search
        position = -1; // Position of search value
        bool found = false; // Flag

        while (!found && first <= last)
        {
              middle = (first + last) / 2; // Calculate mid point
              if (array[middle] == value) // If value is found at mid
              {
                  found = true;
                  position = middle;
              }
              else if (array[middle] > value) // If value is in lower half
                 last = middle - 1;
              else
                 first = middle + 1; // If value is in upper half
        }
return position;
}



    // "Number %d Found at Position %d". Where the
    //first %d is the number the user is searching for
    // and the second %d is the location in the SORTED ARRAY.
    //Else display "Number %d Not Found", where you will put the number the user is searching for in place of %d. You can use either printf() or cout.


    // search continues until they hit Q since it's a loop.


To read the numbers into an array consider (not tried):

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
const int SIZE = 200;
int numbers[SIZE];
int count = 0;

int main()
{
    // prompt user to enter file name. also display if it exists or not
    string filename;

    // Get file name from the user
    cout << "Enter the file name: ";
    cin >> filename;

    // Open the file
    ifstream inputFile(filename);

    // If the file opened successfully, process it
    if (!inputFile)
    {
        // display an error message if the file was not found
        cout << "Error opening the file.\n";
        return 1;
    }

    // Read the numbers from the file and display them.
    for (; (count < SIZE) && (inputFile >> numbers[count]); ++count);

    // Close the file
    inputFile.close();

    // Display the array
    for (int i = 0; i < count; ++i)
        cout << numbers[i] << endl;

    return 0;
}

Last edited on
Hello FanOfThe49ers,

You use a file for input. Please post the contents of the file or at least a fair sample so everyone can see what you have to work with an use the same information.

The first question is what standard is your IDE/compiler set to use? PreC++11, C++11 or beyond. It also helps to know what IDE/compiler you are using.

I rearranged the beginning of the code a bit.

This should be a little easier to read and follow. Note the comments I added.
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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

constexpr int SIZE{ 200 };

int binarySearch(int array[], int size, int value);
void selectionSort(int array[], int size);

int main()
{
    int numbers[SIZE]{};  // <--- Moved.
    int count{};  // <--- Moved.
    int idx{};  // <--- You do not have to use this.
    string name, filename;

    // prompt user to enter file name. also display if it exists or not
    ifstream inputFile; // gives access to file

    // Get file name from the user
    cout << "Enter the file name: ";
    cin >> filename;

    // Open the file
    inputFile.open(filename);  // <--- removed the ".c_str()". Not needed from C++11 on.

    // If the file opened successfully, process it
    if (!inputFile)
    {
        // display an error message if the file was not found
        cout << "Error opening the file.\n";

        return 1;
    }

    // Read the numbers from the file and display them.
    while (idx < SIZE && inputFile >> numbers[idx++])  // <--- Could use "idx" or "count here.
    {
        cout << number << endl;
    }

    // Close the file
    inputFile.close();

    return 0;  // <--- Not required, but makes a good break point.
}

Line 7 I try to put first in case you might need it in the prototypes.

Lines 14 and 15 should not be global variables. This is asking for trouble.
https://www.learncpp.com/cpp-tutorial/why-global-variables-are-evil/

Line 20 could be done in 1 line as: ifstream inputFile(filename);. Although you would need to move line 20 to line 27.

Lines 23 and 24. Is a nice idea except you do not give the user any idea of what file names are available.

Line 30 is changed. This is all you really need. And it is better programming not to run "main" based on an if/else statement. This way if the file did not open you leave the program to figure out what is wrong.

Line 39, your line 33. Is a good start, but this is where your problem starts. As seeplus and I have used this will read your file, if the file is set up right, of any size or until "idx" or "count" is equal to or would exceed "SIZE".

The simple way is to read directly into the array or you could read into "number" then store it into the array. Your original code creates an array, but you never put anything into it.

seeplus's last for loop for printing the array is good, but I would put that code in a function and pass the array to the function. It does give you an idea of what you can do.

I need to create an input file, but it may not be what you are using, before I can test the program.

Andy
Hello FanOfThe49ers,

After some testing I found the while loop needed to be changed. What I ended up with:
1
2
3
4
5
6
while (idx < SIZE && inputFile >> numbers[idx])
{
    idx++;  // <--- Moved here to get the correct number.

    //cout << numbers[idx++] << endl; // <--- Used for testing. Comment or remove when finished.
}

Using "idx++" in the while condition works, but it ends up 1 larger than it should be. You could subtract 1 after the while loop or move "idx++" inside the while loop.

I started with this at the beginning of "main":
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
std::string fileNames[]
{
    "Numbers.txt",
    "Hold.txt",
    "Numbers2.txt"
};

// prompt user to enter file name. also display if it exists or not

std::cout << "\n Available file names.\n " << std::string(15, '-') << '\n';

for (size_t idx = 0; idx < sizeof(fileNames) / sizeof(fileNames[0]); idx++)
{
    std::cout << ' ' << fileNames[idx] << '\n';
}

// Get file name from the user
cout << "\n Enter the file name: ";
cin >> filename;

// Open the file
ifstream inputFile(filename); // gives access to file 


This gives the output of:

 Available file names.
 ---------------
 Numbers.txt
 Hold.txt
 Numbers2.txt

 Enter the file name: Hold.txt

 42,  98,  26,  52,  33,  34,  49,  61,  55,  61
 15,  96,  43,  64,  79,  96,  61,  71,  80,  83
 72,  79,  66,  53,  51,  30,  29,  27,  10,  73
 49,  53,  78,  88,  31,   4,  22,  65,  17,  85
 56,  42,  84,  96,  75,  36,  56,  96,  98,  32
 73,  35,  23,  42,  37,  24,  67,  86,  53,   5
 41,  81,   0,  32,  59,  88,  68,  40,  33,   7
 33,  70,  37,  55,  39,  52,  96,  67,  26,  97
 45,  92,  32, 100,   5,   8,  25,  13,   3,  50

  0,   3,   4,   5,   5,   7,   8,  10,  13,  15
 17,  22,  23,  24,  25,  26,  26,  27,  29,  30
 31,  32,  32,  32,  33,  33,  33,  34,  35,  36
 37,  37,  39,  40,  41,  42,  42,  42,  43,  45
 49,  49,  50,  51,  52,  52,  53,  53,  53,  55
 55,  56,  56,  59,  61,  61,  61,  64,  65,  66
 67,  67,  68,  70,  71,  72,  73,  73,  75,  78
 79,  79,  80,  81,  83,  84,  85,  86,  88,  88
 92,  96,  96,  96,  96,  96,  97,  98,  98, 100


 Enter a number to search for: 42

 The search number index is: 35 and the value is: 42


Something to consider.

Andy

Edit: After line 19 I added std::cout << '\n';
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::string fileNames[]
{
    "Numbers.txt",
    "Hold.txt",
    "Numbers2.txt"
};

// prompt user to enter file name. also display if it exists or not

std::cout << "\n Available file names.\n " << std::string(15, '-') << '\n';

for (size_t idx = 0; idx < sizeof(fileNames) / sizeof(fileNames[0]); idx++)
{
    std::cout << ' ' << fileNames[idx] << '\n';
}


If the array is in scope (and not degenerated to a pointer), then range-for can be used as std::begin() and std::end() are defined. Consider:

1
2
3
4
5
6
7
8
9
10
11
	const std::string fileNames[]
	{
		"Numbers.txt",
		"Hold.txt",
		"Numbers2.txt"
	};

	std::cout << "\n Available file names.\n " << std::setw(15) << std::setfill('-') << '\n';

	for (const auto& n : fileNames)
		std::cout << ' ' << n << '\n';


Note that std::string isn't needed to display the line of -'s.
C++20 has std::span() which makes passing 1-d arrays to functions so much easier:

1
2
3
4
5
void selectionSort(std::span<int> array){
    auto size = array.size();
//....

selectionSort(numbers);


See https://en.cppreference.com/w/cpp/container/span

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void show(std::span<int> array)
{
	std::cout << "size: " << array.size() << std::endl;

	for (const auto& i : array)
		std::cout << i << "  ";
}

int main() {

	int arr[] {1,2,3,4,5};

	show(arr);
}



If you don't have std::span() yet, then you can use a templated function to pass an array without having to also pass its size:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<size_t size>
void show(int (&array)[size])
{
	std::cout << "size: " << size << std::endl;

	for (const auto& i : array)
		std::cout << i << "  ";
}

int main() {
	int arr[] {1,2,3,4,5};

	show(arr);
}

Last edited on
Topic archived. No new replies allowed.