2009-11-16 210 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