Cout was not declared in this scope как исправить

error: ‘cout’ was not declared in this scope C++ Решение и ответ на вопрос 283844

dr.Dozer

22 / 22 / 2

Регистрация: 05.12.2010

Сообщений: 81

1

26.04.2011, 18:02. Показов 88062. Ответов 7

Метки нет (Все метки)


Начал осваивать C++ сегодня и уже столкнулся с проблемой компилятор показывает ошибку:
error: ‘cout’ was not declared in this scope
компилю на minte 9 росинка.

C++
1
2
3
4
5
6
7
#include <iostream>
 
int main()
{
  cout << "Hello world!!!n"; Сдесь ошибка: error:cout’ was not declared in this scope
  return 0;
}

В чем дело?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



1



fasked

Эксперт С++

5038 / 2617 / 241

Регистрация: 07.10.2009

Сообщений: 4,310

Записей в блоге: 1

26.04.2011, 18:13

2

C++
1
std::cout



1



22 / 22 / 2

Регистрация: 05.12.2010

Сообщений: 81

26.04.2011, 18:17

 [ТС]

3

Заработало Еще один вопрос: В книге написано просто cout, может чего ни хватает в прастранстве имен?



0



Эксперт С++

623 / 467 / 57

Регистрация: 28.01.2011

Сообщений: 605

26.04.2011, 18:20

4

В книге, видимо, подразумевается, что в коде имеется запись «using namespace std;», которая позволяет не приписывать каждый раз std:: .



4



0 / 0 / 0

Регистрация: 30.08.2012

Сообщений: 5

30.08.2012, 21:54

5

Вот и я мимо этих граблей не прошел…
Кстати добавление std:: перед cout на моем компиляторе не сработало (пользуюсь minGW), а вот вставка using namespace std; помогла.
Отсюда у меня вопрос — книжки пишутся под конкретные компиляторы, хотя в них утверждается о универсальности их «рецептов»?



0



Псевдослучайный

1946 / 1145 / 98

Регистрация: 13.09.2011

Сообщений: 3,215

30.08.2012, 21:57

6

Цитата
Сообщение от cepxuo
Посмотреть сообщение

Кстати добавление std:: перед cout на моем компиляторе не сработало (пользуюсь minGW), а вот вставка using namespace std; помогла.

Что-то сделали не так, должно было помочь.



1



0 / 0 / 0

Регистрация: 30.08.2012

Сообщений: 5

30.08.2012, 23:17

7

Прошу прощения, ввел в заблуждение (себя больше всего, std:: тоже помогает). В моем случае программа не запускалась из-за строчки #include<iostream.h>(из книги Либерти), пробовал так же #include»std_lib_facilities.h»(Cтрауструп, книга 2011 года, рекомендуемая к прочтению на форуме), помогло только после плясок с бубном (подборов всевозможных вариантов io.h, stdio.h…) #include<iostream>, хотя и про std::(спасибо fasked, Ma3a) в этих трудах так же ничего не было…
Потому у меня возник этот вопрос. Хотя это скорее и не вопрос, скорее это недоумение.



0



alkagolik

Заблокирован

31.08.2012, 02:54

8

Цитата
Сообщение от cepxuo
Посмотреть сообщение

В моем случае программа не запускалась из-за строчки #include<iostream.h>

просто книжечка старовата. суффикс .h уже давно в с++ отменен, а libc объявляются как <cheader>, например <cmath>, <clocale>, etc



2



Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

In this article, we have explored the reason behind the compilation error «cout was not declared in this scope» and how to fix it.

Table of contents:

  1. Reason for error
  2. Fix 1: using namespace
  3. Fix 2: Scope resolution operator

The quick fix is to add the following line in your C++ code just after the include statements:

using namespace std;

Reason for error

While compiling a C++ code, you may get this compilation error:

'cout' was not declared in this scope

If you compile this C++ code, you will get this compilation error:

#include <iostream>

int main() {
    std::cout << "data" << std::endl;
    return 0;
}

Fix 1: using namespace

The easiest fix is to add the code line «using namespace std;» at the top of the code after include statements. This tells the compiler that functions like cout and endl are under the namespace std.

using namespace std;

Following is the complete working C++ code:

#include <iostream>
using namespace std;

int main() {
    cout << "data" << endl;
    return 0;
}

Fix 2: Scope resolution operator

An alternative fix is to add the namespace std with cout and endl using the scope resolution operator. Following are the required changes:

  • Replace «cout» with «std::cout»
  • Replace «endl» with «std::endl»

Following is the complete working C++ code:

#include <iostream>

int main() {
    std::cout << "data" << std::endl;
    return 0;
}

With the fixes in this article at OpenGenus, you must have solved this issue. Continue with your C++ development.

Table of Contents

Common G++ Errors

Summary

This is a guide to help you CS35ers make sense of g++ and its often cryptic error messages.

If you discover an error not listed here feel free to edit this wiki,
or send your error along with source code and an explanation to me — grawson1@swarthmore.edu

Weird Errors

If you are getting strange compiler errors when your syntax looks fine, it might be a good idea to check that your Makefile is up to date
and that you are including the proper .h files. Sometimes a missing } or ; or ) will yield some scary errors as well.
Lastly, save all files that you might have changed before compiling.

Bad Code Sample

What’s wrong with the following code? (Hint: there are two errors)

#include<iostream>
using namespace std;
 
int main(){
 
  int foo;
 
  for(int i = 0, i<100, i++) {
    foo++;
    cout << foo << endl;
  }
  return 0;
}

When compiled this yields:

junk.cpp:9: error: expected initializer before '<' token

junk.cpp:13: error: expected primary-expression before 'return

junk.cpp:13: error: expected `;' before 'return

junk.cpp:13: error: expected primary-expression before 'return

junk.cpp:13: error: expected `)' before 'return

First, the parameters of the for loop need to be separated by semicolons, not commas.

for(int i = 0; i<100; i++) {
    foo++;
    cout << foo << endl;
  }

Now look at this sample output of the corrected code:

-1208637327

-1208637326

-1208637325

-1208637324

-1208637323

-1208637322

Why the weird values? Because we never initialized foo before incrementing it.

 int foo = 0;

‘cout’ was not declared in this scope

Two things to check here:

(1) Did you add

 #include<iostream> 

to your list of headers?
(2) Did you add

 using namespace std; 

after your #includes?

‘printf’ was not declared in this scope

Add

 #include<cstdio> 

to your list of headers. Note if you are coming from C programming, adding
#include<cstdio> is preferred in C++ over #include <stdio.h>.

Cannot Pass Objects of non-POD Type

junk.cpp:8: warning: cannot pass objects of non-POD type 'struct std::string' through '…'; call will abort at runtime

junk.cpp:8: warning: format '%s' expects type 'char*', but argument 2 has type 'int

What this usually means is that you forgot to append .c_str() to the name of your string variable when using printf.

This error occurred when trying to compile the following code:

int main(){
 
  string foo = "dog";
  printf("This animal is a %s.n",foo);
  return 0;
}

Simply appending to .c_str() to “foo” will fix this:

printf("This animal is a %s.n",foo.c_str());

The reason you got this error is because printf is a C function and C handles strings differently than C++

Invalid Use of Member

junk.cpp:8: error: invalid use of member (did you forget the '&' ?)

What this usually means is that you forget to add () to the end of a function call.

Ironically, every time I see this it is never because I forgot the ‘&’.
This error occurred when trying to compile the following code:

int main(){
 
  string foo = "dog";
  printf("This animal is a %s.n",foo.c_str);
 
  return 0;
}

Simply adding the open and close parentheses () will take care of this for you:

printf("This animal is a %s.n",foo.c_str());

Request for Member ‘Foo’ in ‘Bar’, which is of non-class type ‘X’

trycredit.cpp:86: error: request for member 'print' in 'card', which is of non-class type 'CreditCard*

What this usually means is that you are using a ‘.’ between the class pointer and the function you are trying to call.
Here is an example from the CreditCard lab:

void useCard(CreditCard *card, int method) {
  //Used to access the methods of the class
 
  if (method==1) {
    card.print();
  }

Since card is a CreditCard* we need → rather than . Fixed:

  if (method==1) {
    card->print();
  }

Undefined Reference to V Table

This error usually means you need to add a destructor to your myClass.cpp/myClass.inl code.
If you don’t want to implement a real destructor at this point, you can write something like this:

myClass::~myClass(){}

So long as the destructor exists, you should now be able to compile fine. Of course,
implement a real destructor at a later point.

  • Forum
  • Beginners
  • error: ‘cout’ was not declared in this s

error: ‘cout’ was not declared in this scope

I am trying to use a program to calculate BMI with modules. I have started with the following code (could be very wrong but I am a beginner). Can someone help me understand why I am getting an error of error: ‘cout’ was not declared in this scope?

#include <iostream>
double height, weight;
double bmiCal (double height, double weight);

void BMIcalc()

{
cout << «This program will calculate BMI» << endl;

std::cout << "This program will calculate BMIn";

cout belongs to the std namespace, so one has to communicate that to the compiler. I put n rather than endl because that can be a little inefficient — it flushes the buffer every time.

Please always use code tags: http://www.cplusplus.com/articles/z13hAqkS/

Hi ositamay11,

My first thought is based on the code you posted is that

should be

Or you could start your code

1
2
3
4
5
6
#include <iostream>

using namespace std;

double height, weight;
double bmiCal (double height, double weight);

That is the quick answer. I know that the

dose save some typing. And I know there is a better explanation of how it all works maybe some one else can explain it better.

using namespace std; 0r
std::cout《"blah blah"
Either of then would work. The first one is not considered a good practice as apparentely it makes program slower but at this level, it is insignificant.

The problem with using namespace std; is that it can cause naming conflicts (it brings into the global namespace all of std that is in whatever header files one has included), and undermines the whole purpose of having namespaces — which is to help prevent naming conflicts. There are lots of ordinary English words that exist in std, such as left, right which are both defined in iostream. So if one had a variable or function named left, there is a conflict with std::left. It’s worse the more includes one has — especially with the algorithm header file.

It might seem easy to have using namespace std; now, but it will bite you one day.

It is possible to do this:

1
2
3
using std::cout;
using std::cin;
using std::endl;

but that gets tiresome as well, it’s easy to accumulate lots of them. The easiest thing to do in the end is to get put std:: before every std thing. That is what all the experienced coders do, so one might as well get ahead of the game now :+)

Also, using std:: is explicit — std::copy means just that, not boost::copy or some other copy from a different library.

Ideally one should put their own code into it’s own namespaces.

Topic archived. No new replies allowed.

AlexL


  • #1

Здравствуйте! в общем, суть такая: при компилировании в Code: :Blocks выдает ошибку:
‘cout’ was not declared in this scope
Как быть? Кто виноват? И что делать?

#include <iostream>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
//using namespace std;
int main () {
clrscr();
int n;
double r,l,h,s,sb;
cout<<» Vvedite geometricheskoe telo: n»;
cout<<» 1: kub n»;
cout<<» 2: shar n»;
cout<<» 3: cilindr n»;
cout<<» 4: konus n»;
cin>>n;
if (n>=0 && n<=4)
switch (n) {
case 1:
cout<< «vvedite dlinu storon kuba «; cin>>l;
s=6*l*l;
cout<<«n Plochad kuba: » <<s; break;
case 2:cout<<«Vvedite radius shara «; cin>>r;
s=4*3.14*r*r;
cout<< «n Plochad shara: » <<s; break;
case 3:cout<< «Vvedite radius cilindra «; cin>>r>> «n «;
cout<< «Vvedite visotu cilindra «; cin>>h;
sb=2*3.14*r*h;
s=sb+2*3.14*r*r;
cout<< «n Plochad bokovoi poverhnosti cilindra: » <<sb<< «n «;
cout<< «n Plochad polnoi poverhnosti cilindra: » <<s; break;
case 4:cout<< «Vvedite radius konusa «; cin>>r>>»n «;
cout<< «Vvedite dlinu obrazuychei konusa «; cin>>l;
sb=3.14*r*l;
s=sb+3.14*r*r;
cout<< «n Plochad bokovoi poverhnosti konusa: » <<sb<<«n «;
cout<< «n Plochad polnoi poverhnosti konusa: » <<s; break;
default:cout<< «Nepravilnii vibor «; break; }
else cout<< «Neoravilnii vibor»;
getch();

}

да и еще на clrscr (); ругается

Charley2


  • #2

Ну здравствуй!
Попробуй изменить строчку #include<iostream> на #include<iostream.h>

AlexL


  • #3

пробовал, еще больше ошибок выдает :facepalm:

Trupik


  • #4

Раскомментируй строку

. :trash:

DarkKnight


  • #5

C++:

#include <iostream>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
using namespace std;

int main () {
//clrscr();
int n;
double r,l,h,s,sb;
cout<<" Vvedite geometricheskoe telo: n";
cout<<" 1: kub n";
cout<<" 2: shar n";
cout<<" 3: cilindr n";
cout<<" 4: konus n";
cin>>n;
if (n>=0 && n<=4)
switch (n) {
case 1:
cout<< "vvedite dlinu storon kuba "; cin>>l;
s=6*l*l;
cout<<"n Plochad kuba: " <<s; break;
case 2:cout<<"Vvedite radius shara "; cin>>r;
s=4*3.14*r*r;
cout<< "n Plochad shara: " <<s; break;
case 3: cout<< "Vvedite radius cilindra "; cin>>r;//>> "n ";
cout<< "Vvedite visotu cilindra "; cin>>h;
sb=2*3.14*r*h;
s=sb+2*3.14*r*r;
cout<< "n Plochad bokovoi poverhnosti cilindra: " <<sb<< "n ";
cout<< "n Plochad polnoi poverhnosti cilindra: " <<s; break;
case 4:cout<< "Vvedite radius konusa "; //cin>>'n';
cout<< "Vvedite dlinu obrazuychei konusa "; cin>>l;
sb=3.14*r*l;
s=sb+3.14*r*r;
cout<< "n Plochad bokovoi poverhnosti konusa: " <<sb<<"n ";
cout<< "n Plochad polnoi poverhnosti konusa: " <<s; break;
default:cout<< "Nepravilnii vibor "; break; }
else cout<< "Neoravilnii vibor";
getch();

}

См. закомментированные фрагменты, кроме clrscr() (я просто использую комп. микрософа), не стоит записывать в стандартный поток ввкода CIN, лишнии символы, и Win и *nix-системы на них очень плозо реагируют…

Vunderkind


  • #6

Здравствуйте! в общем, суть такая: при компилировании в Code: :Blocks выдает ошибку:
‘cout’ was not declared in this scope
Как быть? Кто виноват? И что делать?

Попробуй в место using namespace std; написать std::cout std::cin.Некоторые студии не принимают using namespace std;

Понравилась статья? Поделить с друзьями:
  • Cout does not name a type error
  • Country not allowed как исправить ошибку
  • Counter strike source как изменить язык
  • Counter strike source как изменить прицел
  • Counter strike launcher error