为什么 C++ 中的 getline() 不起作用?(没有匹配的函数调用'getline(std::ofstream&, std::string&)'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18658837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is getline() in C++ not working? (no matching function for call to 'getline(std::ofstream&, std::string&)'
提问by JVE999
I'm trying to read from a file, but C++ is not wanting to run getline()
.
我正在尝试从文件中读取,但 C++ 不想运行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();
}
}
回答by 0x499602D2
std::getline
is designed for use with input stream classes (std::basic_istream
) so you should be using the std::ifstream
class:
std::getline
设计用于与输入流类 ( std::basic_istream
) 一起使用,因此您应该使用std::ifstream
该类:
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 (file.good())
在循环中用作输入的条件通常是不好的做法。试试这个:
while ( std::getline(file, line) )
{
std::cout << line << std::endl;
}
回答by Suvarna Pattayil
std::getline
reads characters from an input streamand places them into a string. In your case your 1st argument to getline
is of type ofstream
. You must use ifstream
std::getline
从输入流中读取字符并将它们放入字符串中。在您的情况下,您的第一个参数getline
的类型为ofstream
。你必须使用ifstream
std::ifstream file;