问题
I'm trying to read from a file, but C++ is not wanting to run getline()
.
I get this error:
C:\main.cpp:18: error: no matching function for call to 'getline(std::ofstream&, std::string&)'
std::getline (file,line);
^
This is the code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
int main(){
string line;
std::ofstream file;
file.open("test.txt");
if (file.is_open())
{
while ( file.good() )
{
getline (file,line);
cout << line << endl;
}
file.close();
}
}
回答1:
std::getline
is designed for use with input stream classes (std::basic_istream
) so you should be using the std::ifstream
class:
std::ifstream file("test.txt");
Moreover, using while (file.good())
as a condition for input in a loop is generally bad practice. Try this instead:
while ( std::getline(file, line) )
{
std::cout << line << std::endl;
}
回答2:
std::getline reads characters from an input stream and places them into a string. In your case your 1st argument to getline
is of type ofstream. You must use ifstream
std::ifstream file;
来源:https://stackoverflow.com/questions/18658837/why-is-getline-in-c-not-working-no-matching-function-for-call-to-getline