簡體   English   中英

從文本文件讀取的Getline

[英]Getline to read from text file

因此,我正在嘗試從文本文件中讀取聯系人的姓名,電話號碼和地址。

#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');

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM