For one of my assignments in school, I was asked to pass integer values from a .txt file into an array for evaluation, but I'm confused on how to put integer values from a .txt file to an array. Could I have help?
Just in case the values from the .txt file is necessary:
#include <iostream>
#include <fstream> // This is the library for the filestream functions
usingnamespace std;
int main()
{
int yourarray[26]; // Consider using dynamic allocation
ifstream yourstream ( filename ); // Declares infile stream; in your case, use "woohoo.txt"
// (with quotation marks)
/* Optional error checking:
if ( ! yourstream.is_open() ) {
return 1;
} */
for (int i = 0; i < 26; i++) { // This loop will be a bit different if you dynamically allocate
yourstream >> yourarray[i];
}
yourstream.close();
return 0;
}
In your case, you know the number of integers you're reading in, so dynamic allocation isn't necessary, but it's a good idea to learn in case you don't know the .txt file's contents.
For the ifstream object, "yourstream" can be any name you choose - make it something descriptive. It just has to be the same name throughout your code. The name you choose doesn't affect anything.
I got that far, but after that, I am trying to display how many numbers in the array are between 0 and 24 with variable "first", but intellisense tells me that the "first" variable that I am trying manipulate in the while loop is not defined, although it's clearly defined there.
That's because you define "first" as an int, but never initialize it. So in the while loop, whenever you increment "first," you're adding 1 to some random integer. In line 28, add "= 0" and it should work perfectly.
Two other suggestions:
1) Move cout << first; (line 37) to inside of the preceding if loop; this way, "first" will only be printed whenever a number is between 0 and 24, instead of printing a huge line of 0s and 1s, in which "first" is printed every time the loop iterates. Additional possibility in this suggestion: print "first" before entering the loop, to show the user its initial value.
2) Change the while loop (lines 30-39) to a for loop! Because you know how many iterations you want, and you increment "i" regularly, a while loop isn't necessary here. It only saves you one line of code (gets rid of the "i++" in line 38), but it's good practice to use for loops when you know the desired number of iterations.