簡體   English   中英

C ++代碼中的getline()函數錯誤

[英]getline() function error in c++ code

有人可以告訴我我在做什么錯,我得到一個錯誤,說沒有在此范圍內聲明的getline().....

沒有匹配的函數來調用getline(char **,size_t *,FILE *&)

    #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.txt\n", 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 language\n", backup);
            }
            else
            {
                fprintf(stderr, "%sis not in the language\n", 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.txt\n");
        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 language\n", backup.c_str());
        }
        else
        {
            fprintf(stderr, "%s is not in the language\n", backup.c_str());
        }
    }

    return 0;
}

您似乎對各種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 );

它需要一個輸入流對象,一個字符串和一個字符定界符(也有沒有定界符的重載)。

posix getline簽名為

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

再次使用定界符(可選)。

現在,在您的代碼中,您傳遞的參數就像調用沒有定界符的posix版本一樣。 如果要使用標准參數,則必須更改參數(即istream對象而不是FILE* )。 我不知道posix是否還可以使用,因為posix與任何C ++標准都不相同。

請注意, fputsFILE*fprintf是C文件處理函數,而不是C ++函數。

您打算用getline(&s, &length, fd)什么? 您是否正在嘗試使用C getline

假設您已正確打開文件,則在c ++中,您的getline應該如下所示: getline(inputStream, variableToReadInto, optionalDelimiter)

  • 您沒有包含<stdio.h>但是您包含了<fstream> 也許使用ifstream fd("input.txt");
  • 什么是A()
  • 如果您嘗試使用C getline ,則using namespace std可能會干擾
  • 為什么要使用printffprintf而不使用cout << xxxxxxfd << xxxxxx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM