Putting a file into an array

I am trying to get the file to read the text points.txt, but it keeps giving me the error on line 16:
no matching function for call to getline(std::ifstreams&, char&)
I do not know what the problem is, but I know it is where the while loop is located. Thanks for your help.
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

[code]
void ReadData(int plyr[], float ppg[], char names [], int Name_Size, int size)
{
ifstream inFile;
int i;

// open file and check for opening errors
inFile.open("points.txt");
if(!inFile)
{
cout << "Error opening points.txt!\n";
exit (102);

}
i = 0;
// read the data
while(i < size && !(getline(inFile, names[i]).eof()))

{
inFile >> plyr[i] >> ppg[i];
inFile.ignore();

// validate the numbers
if(plyr[i] < 0 || plyr[i] > 99 || ppg[i] < 0)
{
cout << "Error: invalid data\n";
plyr[i] = 0;
ppg[i] = 0;
}
i++;
}
// debug
for(i = 0; i < size; i++)
cout << names[i] << endl << " " << plyr[i] << " " << ppg[i] << endl;
inFile.close();


}

{code}
Last edited on
The version of getline() you're trying to use is for std::strings, not C-strings. There is a different version of the function for C-strings. But I recommend that you think about switching to std::strings if possible.

http://www.cplusplus.com/reference/istream/istream/getline/
The problem is trying to read a whole line into a single character - char names [] is an array of characters.

I'd suggest something like this:
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
int ReadData(int plyr[], float ppg[], string names [], int size)
{
    // open file and check for opening errors
    ifstream inFile("points.txt");
    if (!inFile)
    {
        cout << "Error opening points.txt!\n";
        exit (102);
    }
    
    int i = 0;
    // read the data
    
    while (i < size && getline(inFile, names[i])    && (inFile >> plyr[i] >> ppg[i]))
    {
        inFile.ignore();
        
        // validate the numbers
        if (plyr[i] < 0 || plyr[i] > 99 || ppg[i] < 0)
        {
            cout << "Error: invalid data\n";
            plyr[i] = 0;
            ppg[i] = 0;
        }
        i++;
    }
    
    // debug
    for (int n = 0; n < i; n++)
        cout << names[n] << endl << " " << plyr[n] << " " << ppg[n] << endl;
        
    return i;
}


Here the value returned by the function is the number of items read into the arrays.

Notice also line 29, I use i, rather than size to set the limit of the loop.
Last edited on
Topic archived. No new replies allowed.