c++ - Getline 从文本文件中读取
问题描述
所以,我试图从文本文件中读取联系人的姓名、号码和地址。
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include "stdafx.h"
#include "Person.h"
#include "PhoneBook.h"
void readFromFile(string filename)
{
int n = 0, i;
string temp_name, temp_number, temp_adress, nstr;
ifstream fin(filename.c_str());
getline(fin, nstr);
n = atoi(nstr.c_str());
for (i = 0; i < n; i++)
{
getline(fin, temp_name);
getline(fin, temp_number);
getline(fin, temp_adress);
contactbook->addPerson(temp_name, temp_number, temp_adress);
}
}
main 传递文件名。但我不确定为什么会出现此错误:
错误 C2780 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem)':需要 3 个参数 -提供 2 个
解决方案
我认为您正在使用具有自己编译器的 Visual Studio。正如文档解释的那样,函数 string::getline 有这个声明
template<class _E, class _TYPE, class _A> inline
basic_istream<_E, _TYPE>& getline(
basic_istream<_E, _TYPE>& Istream,
basic_string<_E, _TYPE, _A>& Xstring,
const _E _D=_TYPE::newline( )
);
所以你缺少一个参数,在你的情况下是'\ n'。试试这个代码
void readFromFile(string filename)
{
int n = 0, i;
string temp_name, temp_number, temp_adress, nstr;
ifstream fin(filename.c_str());
getline(fin, nstr,'\n');
n = atoi(nstr.c_str());
for (i = 0; i < n; i++)
{
getline(fin, temp_name,'\n');
getline(fin, temp_number,'\n');
getline(fin, temp_adress,'\n');
}
}
推荐阅读
- django - 如何在 Django 的自定义注册模板中显示错误消息
- django - 通过管理小部件将不正确的经度/纬度保存到 PointField
- c++ - 单例翻译单元混淆
- c++ - qt:执行步骤“Make”时出现RCC解析错误
- html - 如何将滚动条添加到带有滚动条的元素内的元素?
- python - python导入系统的说明
- jquery - 如何通过jquery中的(this)选择器重置表单?
- javascript - React + Webpack 我在做什么错
- x86 - 全局不可见的加载指令
- sass - 在 AngularDart 5 和 Dart 2 中使用 SCSS 样式文件