Visual C++ Visual Studio.net で、int型データをcoutでコンソール画面に出力するプログラムを作成しました。
coutを_tmainの中で使用すると、”10”と期待どおりの結果が出力されましたが、以下のように自作関数printを作成して、print関数の中でcoutを使用すると、
c:\documents and settings\hikino yasuhiro\my documents\visual studio projects\ファイル操作\ファイル操作\ファイル操作.cpp(20) : error C2065: 'cout' : 定義されていない識別子です。
c:\documents and settings\hikino yasuhiro\my documents\visual studio projects\ファイル操作\ファイル操作\ファイル操作.cpp(20) : error C2065: 'endl' : 定義されていない識別子です。
と表示されました。
print関数には#include<iostream>がかかっていないのでしょうか?
ちなみに、print関数内でcoutの代わりにprintfを使用すればコンパイルできました。
回答よろしくお願いいたします。
//自作プログラム//
#include "stdafx.h"
#include <iostream>
void print(int a);
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
int a = 10;
print(a);
getchar();
return 0;
}
void print(int a)
{
cout << a << endl;
}
ネームスペースをつけるか、using namespaceしてください。
>cout << a << endl;
std::cout << a << std::endl;
参考
ロベールのC++教室 - 第1章 業界のスタンダード -
http://www1.kcn.ne.jp/~robe/cpphtml/html04/cpp04001.html
元発言者様の例題では using namespace std; が _tmain() の { } 内部にあるので
その効力が対応する { } の中にとどまってしまうのですな。
1.print() の { } の中にも using namespace std; を書く
2.大域に効くよう { } の外で using namespace std; を書く
3.using みたいな強引な手法はやめて毎回 std::cout std::endl と書く
>using namespace std; が _tmain() の { } 内部にあるので
見落としていました。orz
Blue様、tetrapod様
回答ありがとうございました。おかげで無事解決しました。
やはりstudio.netの基本ともいえるところでしたね。
_tmain()の中ではしっかりusing namespace std;書いてるのに!
勉強不足で恥ずかしい限りです。
本当にこのたびはありがとうございました。
気になったので一つ訂正しておきます。
>やはりstudio.netの基本ともいえるところでしたね。
「C++の基本」の間違いです。
ツイート | ![]() |