2016-09-15 21 views
-3

我正在製作一個帶有嬰兒名稱列表的程序,但我決定打開一個獨立的函數來打開文件,這是我目前爲止所獲得的。.txt函數沒有鏈接到主函數

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

using namespace std; 


void open_file(ifstream& in, char fileName[]); 
void find_name(ifstream& in, string name, int numNames); 



int main() { 

    const int NUMNAMES = 1000; 
    ifstream inStream; 
    char fileName[30]; 
    string name; 
    cout << "Enter the name of the file that contains the names: " << endl; 
    open_file(inStream, fileName); 
    cout << "Enter the name to search for (capitalize first letter): " << endl; 
    cin >> name; 
    find_name(inStream, name, NUMNAMES); 
    inStream.close(); 

} 


void open_file(ifstream&) { 

    string line; 
    ifstream myfile ("babyNames.txt"); 
    if (myfile.is_open()) 
    { 
     while (getline (myfile,line)) 
     { 
      cout << line << '\n'; 
     } 
     myfile.close(); 
    } 

    else cout << "I/O failure opening file babyNames"; 


} 

有誰知道爲什麼我得到這麼多的錯誤消息:

Undefined symbols for architecture x86_64: 
    "find_name(std::__1::basic_ifstream<char, std::__1::char_traits<char> >&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, int)", referenced from: 
     _main in Untitled-1b6d2e.o 
    "open_file(std::__1::basic_ifstream<char, std::__1::char_traits<char> >&, char*)", referenced from: 
     _main in Untitled-1b6d2e.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

有誰知道我做錯了,我覺得這是比較接近的,我只是相當新的流在C++中。

+0

定義所需的功能並將它們鏈接起來。 – MikeCAT

回答

0

所顯示的代碼聲明並調用以下功能:

void open_file(ifstream& in, char fileName[]); 
void find_name(ifstream& in, string name, int numNames); 

不幸的是,所示的代碼沒有定義任何的這兩個函數,這兩個鏈接錯誤是這個結果。

顯示的代碼確實定義了一些函數,也稱爲open_file(),但它是一個完全不同的函數,因爲它需要不同的參數。顯示的代碼沒有定義任何稱爲find_name()的功能。

你不能簡單地聲明像一個函數:

void open_file(ifstream& in, char fileName[]); 

,然後期望代碼此功能自動某處出現。你必須定義並寫出這個函數的內容。當你定義它時,這個函數中的參數必須和你在這裏聲明的相同。