2014-09-10 108 views
-2

我想創建我自己的str複製函數。我得到一個錯誤,告訴我strcopy在這個範圍內沒有被降效 strcopy(deck [i] .suit,source []);是不是我的錯誤發生。請幫助!創建我自己的strcopy函數

#include <fstream> 
#include <iostream> 
using namespace std; 

struct{ 
char suit[]; 
char rank[]; 
int cvalue; 
}; 
int main() 
{ 
char source[] = "name"; 
cards deck[52]; 

strcopy(deck[].suit,source[]); 
} 

void strcopy(char destination[], char source[]) 
{ 
for(int i=0; source[i] != '\0' && destination[i] != '\0'; i++) 
{ 
destination[i] = source[i]; 
} 
} 
+0

編譯器錯誤是正確的。在您嘗試使用它的地方未聲明「strcopy」。它後來被聲明,但C++編譯器是天真的,它需要知道該函數存在於被調用的地方。 – jalf 2014-09-10 17:07:31

+0

請至少google你的錯誤。 – djechlin 2014-09-10 17:10:22

+0

感謝所有的幫助傢伙,即時通訊學習代碼,所以我做了一些新手的錯誤。 @djechlin,去鍛鍊什麼的吧。 theres真的不需要隱藏在你的電腦後面,並且是無禮的 – matt 2014-09-10 17:39:35

回答

0

首先你忘了指定結構的名稱。我認爲它應該有名稱cards

同樣在結構中定義的數組必須被定義爲具有大小。

struct{ 
char suit[]; // What is the size of the array? 
char rank[]; // What is the size of the array? 
int cvalue; 
}; 

函數strcopy必須在其語句之前聲明。

而功能本身是錯誤的。

我沒有發明功能的新算法,並把它寫在下面的方式

char * strcopy(char destination[], const char source[]) 
{ 
    char *p = destination; 

    while (*p++ = *source++); 

    return destination; 
} 
+0

我重新輸入了它,即時發佈在我的真實計算機上,並在虛擬盒子中進行編程,並且這種方式更簡單,但必須留下卡片。我在數組中指定了值。我的行動功能有什麼問題? – matt 2014-09-10 17:19:37

+0

@jalf該函數沒有意義。首先,如果目標數組從零開始並且不復制終止零,它將不會複製任何內容。 – 2014-09-10 17:24:56

+0

我看到我錯了,非常感謝你! – matt 2014-09-10 17:38:29

0

你的編譯器之前知道有一個你正在使用「strcopy」功能。在C/C++中,您必須將其定義在頂層,或者通過提供函數的原型來提供信息。

因此,無論移動它,像這樣:

void strcopy(char destination[], char source[]) 
{ 
    for(int i=0; source[i] != '\0' && destination[i] != '\0'; i++) 
    { 
     destination[i] = source[i]; 
    } 
} 

int main() 
{ 
    char source[] = "name"; 
    cards deck[52]; 

    strcopy(deck[].suit,source[]); 
} 

或添加protoype使用它之前:

void strcopy(char destination[], char source[]); 

int main() 
{ 
    char source[] = "name"; 
    cards deck[52]; 

    strcopy(deck[].suit,source[]); 
} 

void strcopy(char destination[], char source[]) 
{ 
    for(int i=0; source[i] != '\0' && destination[i] != '\0'; i++) 
    { 
     destination[i] = source[i]; 
    } 
} 

欲瞭解更多信息,你可以看到它在維基太:
http://en.wikipedia.org/wiki/Function_prototype

爲了更好的可讀性,我還構建了您的代碼;)