2016-12-12 2 views
0

私は、私は別の文字列に1つの文字列をコピーするには、このプログラムをしようとしていたが、それはプログラムのエラー "エラーC3861: 'copyString':識別子が見つかりません"、なぜ教えてください?

"error C3861: 'copyString': identifier not found" 

エラーを見せてここで私はどこを教えてください

#include <iostream> 
using namespace std; 
int main() 
{ 
    char a[8], b[8]; 
    cout << "enter the string a"; 
    cin.get(a, 8); 
    cout << a; 
    int len = sizeof(a)/sizeof(char); 
    copyString(a, b); 
    int i; 
    cin >> i; 
    return 0; 
} 

/*function that copy one string to another*/ 

void copyString(char* a, char* b) 
{ 
    int i = 0; 
    while (a[i] != '\0') { 
     b[i] = a[i]; 
     i++; 
    } 
    cout << b << " String is this"; 
} 

を書いたコードは、プログラミングに新しいですよ私は間違っている?

+3

前方宣言 –

+0

あなたの主な問題ではありませんが、修正する必要があります: 'cin.get'はヌルで終わる文字列を読みません。ヌルターミネータをチェックする 'copyString'を呼び出す前に、ヌルターミネータを(オーバーフローバッファなしで)手動で追加する必要があります。 –

+0

この質問は記憶を取り戻す! – rmist

答えて

2

どちらかmaincopyString実装を提供する、または最初のそれのためのプロトタイプを提供します。

void copyString(char *a,char *b); // prototype of copyString 
int main() 
{ 
    ... 
} 
void copyString(char *a,char *b) // implementation of copyString 
{ 
    ... 
} 
+0

この場合、関数の順序を入れ替えることをお勧めします。フォワード宣言に変更を加える可能性を排除しますが、実装に同じことをするのを忘れてしまいます。 – user4581301

+0

@ user4581301が合意しています。この単純なケースでは、実際にはプロトタイプは必要ないかもしれません。しかし、より長いソースコードの場合、プロトタイプは実際に読書を助けるでしょう。 – artm

2

C++コンパイラは、関数や変数が使用される前に宣言を提供する必要があります。あなたの問題を解決するには、main()の前にcopyString()の前方宣言を置くだけです。 (相互依存して)あなたのプログラムの成長とより多くの機能が追加されたとき

#include <iostream> 
using namespace std; 

void copyString(char* a, char* b); // this is the forward declaration 

int main() 
{ 
    char a[8], b[8]; 
    cout << "enter the string a"; 
    cin.get(a, 8); 
    cout << a; 
    int len = sizeof(a)/sizeof(char); 

    copyString(a, b); 
    int i; 
    cin >> i; 
    return 0; 
} 

/*function that copy one string to another*/ 
void copyString(char* a, char* b) 
{ 
    /* here is the real implementations */ 
} 

しかし、私は分離ヘッダファイルと容易なメンテナンスのためのソースの中にそれらの機能を分割するために、あなたをお勧めします。

main.cppに

#include <iostream> 
using namespace std; 

#include "my_string_lib.h" // PLEASE notice this line 

int main() 
{ 
    char a[8], b[8]; 
    cout << "enter the string a"; 
    cin.get(a, 8); 
    cout << a; 
    int len = sizeof(a)/sizeof(char); 

    copyString(a, b); // included in my_string_lib.h 
    int i; 
    cin >> i; 
    return 0; 
} 

my_string_lib.h

#pragma once // assume you are using msvc 

/*! 
    Copy the string content from a to b, 
    assume b is allocated large enough to hold a. 
*/ 
void copyString(char* a, char* b); 

my_string_lib.cpp

#include "my_string_lib.h" 

void copyString(char* a, char* b) 
{ 
    /* here is the real implementations for copying a to b*/ 
} 

確認トンをしてくださいhat main.cpp、my_string_lib.cpp、およびmy_string_lib.hは、同じディレクトリ内に配置されます。

関連する問題