| By making it one long concatenated string I am not sure how to separate for the comparison. Hope that made sense. |
I'm glad you recognized this conflict. It shows a knack for understanding programming problems. Can you post the entire problem? That might help us understand what the prof wants.
| Eventually we are to use this array, which will consist of 3 usernames and passwords each on one line |
Okay that's very important. So the maxUsers parameter tells us the maximum number of items in the file. That means that we can allocate space for maxUsers users:
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
|
#include <iostream>
#include <fstream>
using namespace std;
// Read the stream and return its contents
string *getFile(string filename, const int maxUsers, int *size)
{
string *result = new string[maxUsers];
ifstream is(filename.c_str());
*size = 0;
while (*size < maxUsers && getline(is, result[*size])) {
++ *size;
}
return result;
}
int main()
{
int size;
string *lines = getFile("foo.cpp", 20, &size);
for (int i=0; i<size; ++i) {
cout << lines[i] << endl;
}
delete[] lines;
return 0;
}
|
Line 8 allocates an array of maxUsers strings and points result to it.
Lines 10-13 read up to maxUsers strings and store them into sequential strings in the results array. Since
size is a pointer to an int, we have to use *size to access the integer that it points to. Rather than use a local counter read the lines, I'm just using *size.
Line 12 increments the size.
Line 14 returns
result to the caller.
At line 20 we call getFile(), passing it the address of the local variable "size". (
&size). At the same line, the program declares a local variable called lines that points to a string. This variable is assigned the return value from getFile().