C++ 代码中的 getline() 函数错误
getline() function error in c++ code
有人可以告诉我我在这里做错了什么吗,我收到一个错误,说 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
getline
,using namespace std
可能会干扰 - 为什么使用
printf
和fprintf
而不是cout << xxxxxx
和fd << 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++标准都不同。
请注意,fputs
、FILE*
、fprintf
是 C 文件处理函数,而不是C++函数。
相关文章:
- "error: no matching function for call to"构造函数错误
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- C++ OpenCV 卡尔曼滤波器构造函数错误
- C++:用户定义的显式类型转换函数错误
- C++ 合并字符串以'system'函数错误
- C++ wmain 函数错误时使用 Unicode
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- C++ 中常量属性的初始化构造函数错误
- 线程 std::调用未知类型,无法专门化函数错误
- 表单显示对话框函数错误,并且不执行下面的语句
- 函数错误 C2059:语法错误:'>'不起作用
- STL向量上出现奇怪的复制构造函数错误
- C++ Visual Studio 重载函数错误:没有重载函数的实例与指定的类型匹配
- C++引用已删除函数错误
- 为什么通过带有文字编号的引用调用会出现"无匹配函数"错误?
- C++ 乘法定义的构造函数错误消息似乎错误
- 在 c++ 代码中将数组传递给函数错误
- FFMPEG avcodec_decode_video2函数错误代码
- 为什么我会收到转换函数错误