ifstream error

It works fine until I remove grade from following line.
inFile >> Name >> Course >> Age >> Grade;
SAMPLE.txt is given below.

Name Course Age Grade
Nasir Comp1 23 3.1
Jamil Data2 34 4.0
Faisal Prog3 20 2.2
JawaD Hard1 80 3.3

I tried to remove grade from the text file too and tried putting a short e.g (3.0), but that didn't work also.

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



#include <iostream>
#include <fstream>
using namespace std;

main (int argc , char **argv)
{

ifstream inFile;

char Name [100] = "Names";
char Course [50] = "Course";
char Age [20] ={0};
short Grade [20]= {0.0};

inFile.open("SAMPLE.txt", ios_base::in);

if (inFile)
{
cout << "The file opened successfully.\n";

while (!inFile.eof()){
	
	inFile >> Name >> Course >> Age >> Grade;
	cout << Name << "\t" << Course << "\t" << Age << "\t"<< Grade << endl;
};


}
else

cout << "The file didn't open successfully. \n";

cout << Name;

inFile.close();











cout<< "\n\n\n";
system ("pause");
}





26 34 H:\Study\C++\codes\Test.cpp [Error] no match for 'operator>>' (operand types are 'std::basic_istream<char>' and 'short int [20]')

This above line is just one error, there are 81 others too, all vanish once I remove Grade from inFile line. :(
short is an abbreviation for short int. But it should be a floating-point type. It doesn't need to be an array, there is only one grade per student.
1
2
3
4
    char   Name[100]  = "Names";
    char   Course[50] = "Course";
    int    Age        = 0;
    double Grade      = 0.0;


Don't use eof() in a while loop. Instead try this:
1
2
3
4
    while (inFile >> Name >> Course >> Age >> Grade)
    {
        cout << Name << "\t" << Course << "\t" << Age << "\t"<< Grade << endl;
    };
You have an error on line 16 because 0.0 is a double and a narrowing conversion is required to turn it into a short. You should have used an integer literal instead

 
short Grade [20] = {0};

If you want you can leave out the literal. All elements in the array will be initialized to zero as long as you use the braces.

 
short Grade [20] = {};

It's possible to leave out the = symbol as well.


You have an error line 26 because you can't read arrays all at once using the >> operator (It only works with char arrays). What you could do is looping through the 20 elements in the array using a for loop and use the >> operator to read each value.
Last edited on
Topic archived. No new replies allowed.