C++ 代码中的 getline() 函数错误

getline() function error in c++ code

本文关键字:函数 错误 getline 代码 C++      更新时间:2023-10-16

有人可以告诉我我在这里做错了什么吗,我收到一个错误,说 getline() 未在此范围内声明......任何帮助将不胜感激。

调用 getline 没有匹配函数(字符**、size_t*、文件*&)

    #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;
    char *s;
    int main(int argc, char *argv[])
    {
        FILE* fd = fopen("input.txt", "r");
        if(fd == NULL)
        {
            fputs("Unable to open input.txtn", stderr);
            exit(EXIT_FAILURE);
        }
        size_t length = 0;
        ssize_t read;
        const char* backup;
        while ((read = getline(&s, &length, fd) ) > 0)
        {
            backup = s;
            if (A() && *s == 'n')
            {
                printf("%sis in the languagen", backup);
            }
            else
            {
                fprintf(stderr, "%sis not in the languagen", backup);
            }
        }
        fclose(fd);
        return 0;
    }
您需要

使用C++样式代码才能以跨平台的方式使用getline。

#include <fstream>
#include <string>
using namespace std;
std::string s;
bool A() { return true; }
int main(int argc, char *argv[])
{
    ifstream myfile("input.txt");
    if(!myfile.is_open())
    {
        fprintf(stderr, "Unable to open input.txtn");
        return 1;
    }
    size_t length = 0;
    size_t read;
    std::string backup;
    while (getline(myfile, s))
    {
        backup = s;
        if (A() && s == "n")
        {
            printf("%s is in the languagen", backup.c_str());
        }
        else
        {
            fprintf(stderr, "%s is not in the languagen", backup.c_str());
        }
    }
    return 0;
}
你想

getline(&s, &length, fd)做什么?您是否正在尝试使用 C getline

假设您已经正确打开了文件,在 c++ 中,您的getline应如下所示:getline(inputStream, variableToReadInto, optionalDelimiter) .

  • 您没有包括<stdio.h>但确实包括了<fstream>。也许使用ifstream fd("input.txt");
  • 什么是A()
  • 如果您尝试使用 C getlineusing namespace std可能会干扰
  • 为什么使用printffprintf而不是cout << xxxxxxfd << xxxxxx

您似乎对各种getline函数签名有点困惑。

标准C++ std::getline签名是

template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input,
                                           std::basic_string<CharT,Traits,Allocator>& str,
                                           CharT delim );

它需要一个输入流对象、一个字符串和一个字符分隔符(还有一个没有分隔符的重载)。

签名getline

ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);

分隔符再次可选。

现在,在您的代码中传递参数,就像调用不带分隔符的 POSIX 版本一样。如果你想使用标准的,你必须改变参数(即 istream对象而不是FILE*)。我不知道 posix 是否适合您,因为 posix 与任何C++标准都不同。

请注意,fputsFILE*fprintf是 C 文件处理函数,而不是C++函数。