为什么C ++中的getline()无法正常工作? (没有匹配功能可调用"getline(std :: ofstream&amp ;, std :: string&)") [英] Why is getline() in C++ not working? (no matching function for call to 'getline(std::ofstream&, std::string&)'

查看:393
本文介绍了为什么C ++中的getline()无法正常工作? (没有匹配功能可调用"getline(std :: ofstream&amp ;, std :: string&)")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文件中读取,但是C ++不想运行getline().

I'm trying to read from a file, but C++ is not wanting to run getline().

我收到此错误:

C:\main.cpp:18: error: no matching function for call to 'getline(std::ofstream&, std::string&)'
          std::getline (file,line);
                                 ^

这是代码:

#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();
     }


}

推荐答案

std::getline设计用于输入流类(std::basic_istream),因此您应该使用std::ifstream类:

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");

此外,使用while (file.good())作为循环中输入的条件通常是不好的做法.尝试以下方法:

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;
}

这篇关于为什么C ++中的getline()无法正常工作? (没有匹配功能可调用"getline(std :: ofstream&amp ;, std :: string&amp;)")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆