自作関数でcoutを使うには?

解決


grassvalleys  2006-11-10 01:29:06  No: 63556

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;
}


Blue  2006-11-10 01:32:24  No: 63557

ネームスペースをつけるか、using namespaceしてください。

>cout << a << endl;
std::cout << a << std::endl;

参考
ロベールのC++教室 - 第1章 業界のスタンダード -
http://www1.kcn.ne.jp/~robe/cpphtml/html04/cpp04001.html


tetrapod  2006-11-10 02:54:34  No: 63558

元発言者様の例題では using namespace std; が _tmain() の { } 内部にあるので
その効力が対応する { } の中にとどまってしまうのですな。

1.print() の { } の中にも using namespace std; を書く
2.大域に効くよう { } の外で using namespace std; を書く
3.using みたいな強引な手法はやめて毎回 std::cout std::endl と書く


Blue  2006-11-10 03:27:10  No: 63559

>using namespace std; が _tmain() の { } 内部にあるので
見落としていました。orz


grassvalleys  2006-11-10 04:09:09  No: 63560

Blue様、tetrapod様

回答ありがとうございました。おかげで無事解決しました。
やはりstudio.netの基本ともいえるところでしたね。
_tmain()の中ではしっかりusing namespace std;書いてるのに!
勉強不足で恥ずかしい限りです。

本当にこのたびはありがとうございました。


keichan  2006-11-10 20:59:24  No: 63561

気になったので一つ訂正しておきます。

>やはりstudio.netの基本ともいえるところでしたね。
「C++の基本」の間違いです。


※返信する前に利用規約をご確認ください。

※Google reCAPTCHA認証からCloudflare Turnstile認証へ変更しました。






  このエントリーをはてなブックマークに追加