因此,我正在尝试从文本文件中读取联系人的姓名、电话号码和地址。
#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。 作为documentation解释函数 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');
}
}
关于c++ - Getline 从文本文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51723206/