首页 > 解决方案 > 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 个

标签: c++

解决方案


我认为您正在使用具有自己编译器的 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');

    }
}

推荐阅读