[英]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 ++標准都不相同。
請注意, fputs
, FILE*
和fprintf
是C文件處理函數,而不是C ++函數。
您打算用getline(&s, &length, fd)
什么? 您是否正在嘗試使用C getline
?
假設您已正確打開文件,則在c ++中,您的getline
應該如下所示: getline(inputStream, variableToReadInto, optionalDelimiter)
。
<stdio.h>
但是您包含了<fstream>
。 也許使用ifstream fd("input.txt");
A()
getline
,則using namespace std
可能會干擾 printf
和fprintf
而不使用cout << xxxxxx
和fd << xxxxxx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.