2009-11-16 213 views
1
#include<string> 
using namespace std; 

int main(){ 
    const int SIZE=50; 
    int count=0; 
    ifstream fin("phoneData.txt"); 
    ofstream fout("phoneList.txt"); 
    string firstName, lastName, phoneNumber; 
    if (!fin){ 
     cout<<"Error opening file. program ending."<<endl; 
     return 0; 
    } 
    while (count<SIZE && fin>>phoneNumber[count]){ 
     fin.ignore(); 
     getline (fin, firstName[count], '\n'); 
     fin>>lastName[count]; 
     count++; 
    } 
    return 0; 

这是我的代码到目前为止。在我while循环,什么是错与函数getline,我不断收到一个错误信息是这样的:C++编译错误

error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem)' : could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &' from 'std::ifstream' 
1>  c:\program files\microsoft visual studio 9.0\vc\include\string(475) : see declaration of 'std::getline' 

请帮助!我无法弄清楚它!

回答

1
getline (fin, firstName[count], '\n'); 

应该是:

getline(fin, firstName); 

还有更多的问题,太。这里是一个可能的清理,让你的输入数据的几个假设,我无法从你的代码告知:

#include <iostream> 
#include <fstream> 
#include <string> 

int main(){ 
    using namespace std; 
    ifstream fin("phoneData.txt"); 
    ofstream fout("phoneList.txt"); 
    if (!(fin && fout)){ 
    clog << "Error opening file. program ending.\n"; 
    return 1; 
    } 
    const int SIZE=50; 
    string firstName, lastName, phoneNumber; 
    for (int count = 0; count < SIZE; ++count) { 
    getline(fin, phoneNumber, ' '); 
    getline(fin, firstName, ' '); 
    getline(fin, lastName); 
    if (!fin) { 
     break; 
    } 
    fout << lastName << ", " << firstName << " -- " << phoneNumber << '\n'; 
    } 
    return 0; 
} 

输入样本:

123 Marcy Darcy 
555-0701 Daneal S. 

输出样本:

Darcy, Marcy -- 123 
S., Daneal -- 555-0701 
0

http://www.cplusplus.com/reference/string/getline/

这里是getline的签名 istrea m & getline(istream & is,string & str,char delim);

Just do getline(fin,firstName [count] ,'\ n');

请注意'\ n'不是强制性的。默认情况下,它获得整条线。

也许你想声明名字& co作为向量? std :: vector firstName(SIZE);

上的绳子,运营商[]得到一个char http://www.cplusplus.com/reference/string/string/operator%5B%5D/

所以鳍>> lastName的[计]只想读一个字符为姓氏。

+0

你还有'[计]',这是主要的问题。 – 2009-11-16 23:21:24

+0

doh ...确实...谢谢 – 2009-11-17 00:23:30

0

怎么样*流包括 - 只为卫生即使字符串包括他们为你

函数getline(片,名字); //应该可以工作

0

firstName和lastName都不是数组,但是您错误地将它们用作数组类型。

0

我想你正在寻找的是

char firstName[1024] 
fin.getline (firstName, 1024, '\n') 
+0

不,istream :: getline不接受std :: string。 – 2009-11-16 23:20:45

+0

嗯。那是个很好的观点。我会改变代码。 – 2009-11-17 14:40:07