Hello everyone! I am new to this site and a beginner to C++. My problem today is I want to use an array to look at my file "names.txt" then output how many names it found in the file. It does this, for example, it will output:
yourname [0]
yourname [1]
the above will be shown but will also show blanks leading up to 1000. like this:
yourname [0]
yourname [1]
[2]
[3] .. so on till [999]
all I want outputted is the number of names in the file and it can be just a number value without the actual name first.
The problem with arrays, C-style and the new C++ container class, is they are fixed size. You have to declare how big you want the array to be when creating your array variable, so you need to create an array larger than you estimate you will ever need. Wasted RAM with that.
is this even possible using array
Yes, it is possible, you manually increment a count when you read each item from your file. Then when you display your array contents you simple loop only to the number of items you read in. You could rewrite your code to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//store words in array
int count = 0;
while (infile >> line)
{
harray[i] = line;
count++;
}
//output whole array with array position numbers for each entry
cout << "Array contents:\n";
for (int i = 0; i < count; i++)
{
cout << harray[i] << "(" << i << ")" << endl;
}
Thank you both for your help! This has completely solved my problem. I was very confused and embarrassed to admit that I spent more than 2 hours on two different days scratching my head on this one...
Thanks again!