c++ - Getline 从文本文件中读取

标签 c++

因此,我正在尝试从文本文件中读取联系人的姓名、电话号码和地址。

#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/

相关文章:

c++ - 给定一个 DI-Graph。检查所有节点对是否存在来自 (u,v) 或 (v,u) 的路径

c++ - 为什么 C++ 中不存在对成员的引用?

c++ - CORDIC 用于平方根

c++ - 使用 SIMD AVX 计算两个排序数组的对称差异的大小

c++ - CListCtrl 用鼠标选择多行

c++ - 替换 std::stringstream 内联中的字符

c++ - 为什么即使在使用 Qt::DirectConnection 之后,接收方的线程中仍会调用插槽?我如何确保它在另一个线程中被调用?

c++ - 如何在新设计中迁移需要几个额外参数的函数

c++ - 左值绑定(bind)到右值引用

c++ - Visual Studio 在哪里寻找 C++ 头文件?