Reputation: 139
I want to read numbers from a file and I'm having problems with the getline. I have the following code, I'll post the part that matters:
main.cpp
int main() {
GrafNoEtiquetat Graf;
ifstream f_ent;
ofstream f_sort;
string str;
cout << "Introdueix el nom del fitxer a llegir." << endl;
cin >> str;
char *cstr=new char[str.size()+1];
strcpy(cstr, str.c_str());
f_ent.open(cstr);
if(f_ent.fail()) cerr << "El fitxer no s'ha pogut obrir." << endl;
else {
Graf(cstr);
unidireccional(Graf);
delete [] cstr;
cout << "Introdueix el nom del fitxer de surtida" << endl;
cstr = new char [str.size()+1];
strcpy(cstr, str.c_str());
f_sort.open(cstr);
if(f_sort.fail()) cerr << "El fitxer no s'ha creat." << endl;
else Graf.escriureGraf(f_sort);
}
return 0;
}
And here is the function that creates the Graf using const char * cstr:
GrafNoEtiquetat::GrafNoEtiquetat(const char * cstr) {
char c[1000];
int n1, n2;
cstr.getline(c,80);
while(c!="#") {
nNodes++;
cstr.getline(c,80);
}
arestes.resize(nNodes+1);
while(!cstr.eof()) {
cstr >> n1;
cstr >> n2;
afegirAresta(n1, n2);
}
cstr.close();
}
I'm getting errors in all the lines i use 'cstr', at the getline, cstr.eof(), when I read n1 and n2 and when i want to close the file. The errors are similar to the following:
error: request for member 'getline' in 'cstr', which is of non-class type 'const char*'
I don't know why is this happening, any clues?
Upvotes: 0
Views: 727
Reputation: 4012
The error message says exacly what the problem is. There is no getline
method which would be a member of a const char*
.
you define cstr
as const char * cstr
, and then try to call getline
on it: cstr.getline(c,80);
. You should use it to read contents from a istream
, not an array of characters.
If you want to do it your way, do it as follows:
GrafNoEtiquetat::GrafNoEtiquetat(const char * cstr) {
ifstream inputFile(cstr);
char c[1000];
int n1, n2;
inputFile.getline(c,80);
while(c!="#") {
nNodes++;
inputFile.getline(c,80);
}
arestes.resize(nNodes+1);
while(!inputFile.eof()) {
inputFile >> n1;
inputFile >> n2;
afegirAresta(n1, n2);
}
inputFile.close();
}
And you should also check if the file was openned properly. To do that use ifstream::is_open
.
Upvotes: 3