【问题标题】:Getline to read from text fileGetline 从文本文件中读取
【发布时间】:2018-08-07 09:20:18
【问题描述】:

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

#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> &std::getline(std::basic_istream<_elem> &,std::basic_string<_elem> &,const _Elem)':预期3 个参数 - 提供 2 个

【问题讨论】:

  • 1:你不需要它,文件超出范围时会被关闭。 2:std::getline(...)?你已经包含了所需的标题?如果您向我们展示Minimal, Complete, and Verifiable Example,以及错误输出的完整、完整且未经编辑的复制粘贴,则更容易为您提供适当的帮助。
  • 您正在读取的文件格式是什么?
  • 它通常更容易通过std::cin 阅读。有时您需要getline,但如果每行仅包含一个条目,则不需要
  • 标题是:、“stdafx.h”、“Person.h”、“PhoneBook.h”我正在阅读.txt
  • 您实际上是在使用预编译的头文件进行构建吗? VC 可能会忽略 stdafx.h 之前的所有内容 - 想法是您从 stdafx.h 包含您的 C++ 头文件(以及大型不经常更改的项目头文件),并将其作为每个源代码中的第一个包含。但我怀疑这会导致这个问题。

标签: c++


【解决方案1】:

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

    }
}

【讨论】:

  • 是的,我正在使用 VS 2015。我没说,对不起。新错误:错误 C2784 'std::basic_istream<_elem> &std::getline(std::basic_istream<_elem> &,std::basic_string<_elem> &,const _Elem)': 可以不从 'int' 推断出 'std::basic_istream<_elem> &' 的模板参数
  • 每个getline都会导致多个错误,其中一些是旧的C2780,一些是C2784
  • 尝试在getline开头添加std::
  • @Dragonith 你能告诉我错误的原因吗?我有兴趣
  • 在引用 temp_number 和 temp_adress 的函数上缺少 (),初学者错误。抱歉打扰了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 2018-11-01
  • 2016-07-15
  • 2015-06-11
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
相关资源
最近更新 更多