问题
I am having issues figuring out how to properly use getline()
when it comes to classes and objects. I am needing to read in lines of string
type and then add them to the myVec
vector using push_back
. Here is what I have at the moment:
vector<myClass> read_file(string filename)
{
vector<myClass> myVec;
myClass line;
ifstream inputFile(filename);
if (inputFile.is_open())
{
while (inputFile.getline(inputFile, line)) // Issue it here.
{
myVec.push_back(line);
}
inputFile.close();
}
else
throw runtime_error("File Not Found!");
return myVec;
}
Assume the class myClass
is already implemented.
Thanks for the help.
回答1:
Assume the class
myClass
is already implemented.
That doesn't help, we can't just assume it's implemented and know what its interface is or how to use it, so we can't answer your question.
Why do you expect std::ifstream
to know how to work with myClass
? Why are you passing inputFile
as an argument to a member function of inputFile
? Have you looked at any documentation or examples showing how to use getline
?
Assuming you can construct a myClass
from a std::string
this will work (note it reads into a string
and note you don't need to close the file manually):
vector<myClass> read_file(string filename)
{
ifstream inputFile(filename);
if (!inputFile.is_open())
throw runtime_error("File Not Found!");
vector<myClass> myVec;
string line;
while (getline(inputFile, line))
{
myClass m(line);
myVec.push_back(m);
}
return myVec;
}
回答2:
Your usage of getline
doesn't match the signature - you have arguments of wrong type.
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
If you want to add a myClass
element to the vector based on the string you read, you have to construct it first and then push it back.
来源:https://stackoverflow.com/questions/22390500/using-getline-to-read-in-lines-from-a-text-file-and-push-back-into-a-vector-of