Error sin was not declared in this scope

'cin' was not declared in this scope| C++ Решение и ответ на вопрос 2722124

kosdin

13 / 12 / 3

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

Сообщений: 70

1

02.11.2020, 14:41. Показов 3307. Ответов 2

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


Изучаю C++ и столкнулся с такой вот проблемой.
Вот сам код:

C++
1
2
3
4
5
6
7
8
9
10
#include <string>
using namespace std;
 
int main()
{
    string s;
    cin >> s;
    cout << s << endl;
    return 0;
}

Выдаёт вот такие ошибки: ‘cin’ was not declared in this scope; ‘cout’ was not declared in this scope

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



0



Zirak

76 / 68 / 10

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

Сообщений: 320

02.11.2020, 14:45

2

C++
1
#include <iostream>

А using namespace лучше не использовать.



0



kosdin

13 / 12 / 3

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

Сообщений: 70

02.11.2020, 14:47

 [ТС]

3

Уже понял в чём была ошибка, забыл прописать

C++
1
#include <iostream>



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

02.11.2020, 14:47

Помогаю со студенческими работами здесь

Was not declared in this scope
int main()
{
int x=y;
}

int y;

main.cpp: In function ‘int main()’:
main.cpp:3:11:…

‘mean’ was not declared in this scope
здравствуйте,наткнулся на статью,где человек строит лодку на автопилоте,но у меня есть проблема…

‘mean’ was not declared in this scope
здравствуйте,наткнулся на статью,где человек строит лодку на автопилоте,но у меня есть проблема…

‘mean’ was not declared in this scope
здравствуйте,наткнулся на статью,где человек строит лодку на автопилоте,но у меня есть проблема…

Was not declared in this scope
вот мой класс, пишет вот такие ошибки:
error: ‘pow’ was not declared in this scope, так же само с…

Was not declared in this scope
Можете подсказать как исправить. При компиляции выдает ‘strLen’ was not declared in this scope

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

3

  • Forum
  • UNIX/Linux Programming
  • cin,cout,and endl of c++

cin,cout,and endl of c++

Hi,
Dear everybody,I write a program,it includes followed head files:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream.h>
#include <math.h>

But,when I compile it,screen out:
error: `cout’ was not declared in this scope
error: `endl’ was not declared in this scope
error: `cin’ was not declared in this scope
Could please youtell me how can I do,thank you.
wenli wang
th26,August,2010

Add:

1
2
#include <iostream>
using namespace std;

In addition, <fstream.h> is deprecated. Use <fstream> instead. You should also use <cstring>, <cstdio>, <cstdlib> and <cmath> instead of the C (.h) variants.

I recommend that you avoid «using namespace std;» if you can avoid it. Prefer to use «std::cin», «std::cout» and «std::endl» instead. It’s a bad habit that many programmers learn in school that they struggle to break as a professional programmer.

If I can ask, why is that a bad habit?

It’s a bad habit because it’s incorrect. All C++ standard headers (including those from the C library) have no .h suffix. I would assume this is to separate standard headers from user-created/non-standard ones (e.g. the Windows and POSIX APIs)

Ok, but I mean the namespace thing :p

Oh; there are several reasons for that. One of them has to do with name conflicts.

I’d break that habit ASAP, I did; it really isn’t difficult to prefix «std::» to things.

ok..I’ll have a look on google to find why :)

Using namespaces globally is not a bad habit, imo. When creating applications that only use the STL, the C library and standard C++ no naming conflicts should emerge. I do, however agree that you should not make a habit of it. Be wary of the effect of (using) namespaces, so that when things go (horribly) wrong you know what to do.

Is it worth the risk? It probably takes more energy to «Be wary of the effect» than it does to type «std::» a few times.

Namespaces separate and organize functionality. You can have a «xander333::sort()» function and it won’t conflict with «std::sort()» or «boost::sort()» or any other sort(). Without namespaces their can be only one sort().

Now let’s say you’ve put «using namespace std;» in all your source files and you’ve implemented a simple templated function called «fill()» in the global namespace of one of your files. This file also depends on a header from libFoo — «foo.hpp». Version 2.1 of libFoo comes out and all of a sudden your program no longer compiles. You version of «fill()» suddenly conflicts with another «fill()»! What happened???

It turns out that the folks implementing libFoo included <algorithm> in the new version of «foo.hpp» when they didn’t before. Now you have all of the standard algorithms being included in your source file, and your «using namespace std;» has pulled them all into the global namespace. std::fill() now directly conflicts with your fill().

More insidious, you’ve gotten your code to compile by renaming your fill() to xander333_fill(), but something’s not working right — your report numbers are off. It turns out that your custom divides() function, which does fixed precision math, is no longer being called because the templated function from <functional> (also newly included by «foo.hpp») makes for a better match because you’re calling types did not exactly match the declared types.

I try to compile it again using methods given by Kyon and PanGalactic,but fail.I think may be the LD_LIBRARY_PATH environment variables is wrong and computer can not find the head files.I do this in redhat linux enterprise4.8(gnu gcc 3.2.3 or latter)
g++ plot_fitsfile.cc -I/usr/include
But out again:
error: `cout’ was not declared in this scope
error: `endl’ was not declared in this scope
error: `cin’ was not declared in this scope
What should I do?Thank you.

Last edited on

Use std::cout, std::cin, and std::endl.

chrisname wrote:
Is it worth the risk? It probably takes more energy to «Be wary of the effect» than it does to type «std::» a few times.

By «Be wary of the effect» I mean, know what namespaces actually do. Which is slight renaming. Either stating using «using namespace std;» or use «std::..» only are wrong. I personally don’t like using things I don’t know about.

@Wengli Wang: What’s the code you are trying to compile, in it’s full extends?

you will, in time come across occasions when you get name clashes.
then you will understand, grasshopper.

it’s OK for trivial stuff I’d say

Mr Kyon,The length of code is bigger than max length and can’t post here.Could please you send your email address to china.wenli.wang@gmail.com.I will send the codes to you,and please you give me some advice for compile it.Thank you.

mr kyon thanks U so much cause I’l be learn c++ brginner on linux……..

Topic archived. No new replies allowed.

Я просто пытаюсь использовать функции sin, cos и sqrt, но продолжаю получать сообщения об ошибках «не объявлено в этой области». Я просмотрел все результаты поиска на предмет ошибки, и 1. кодировщики используют терминал для компиляции своего кода (а не CodeBlocks, которые я использую) 2. Я пробовал использовать вместо этого cmath , добавив using namespace std и используя абсолютные пути. Я расстраиваюсь.

#ifndef _MATH_H
#define _MATH_H
#include </usr/include/math.h>

#define PI 3.14159265
#define DEG_TO_RAD PI / 180.0f

struct Vector2
{
    float x;
    float y;

    Vector2(float _x = 0.0f, float _y = 0.0f)
        : x(_x), y(_y) {}

    float MagnitudeSqr()
    {
        return x*x + y*y;
    }

    float Magnitude()
    {
        return (float)sqrt(x*x + y*y);
    }

    Vector2 Normalized()
    {
        float mag = Magnitude();

        return Vector2(x/ mag, y /mag);
    }
};

inline Vector2 operator +(const Vector2& lhs, const Vector2& rhs)
{
    return Vector2(lhs.x + rhs.x, lhs.y + rhs.y);
}

inline Vector2 operator -(const Vector2& lhs, const Vector2& rhs)
{
    return Vector2(lhs.x - rhs.x, lhs.y - rhs.y);
}

inline Vector2 RotateVector(Vector2& vec, float angle)
{
    float radAngle = (float)(angle*DEG_TO_RAD);

    return Vector2((float)(vec.x * cos(radAngle) - vec.y * sin(radAngle)), (float)(vec.x * sin(radAngle)) + vec.y * cos(radAngle));
}


#endif // _MATH_H

Без абсолютного пути

||=== Build: Debug in SDL (compiler: GNU GCC Compiler) ===|
/usr/include/c++/7/cmath|83|error: ‘::acos’ has not been declared|
/usr/include/c++/7/cmath|102|error: ‘::asin’ has not been declared|
/usr/include/c++/7/cmath|121|error: ‘::atan’ has not been declared|
/usr/include/c++/7/cmath|140|error: ‘::atan2’ has not been declared|
/usr/include/c++/7/cmath|161|error: ‘::ceil’ has not been declared|
/usr/include/c++/7/cmath|180|error: ‘::cos’ has not been declared|
/usr/include/c++/7/cmath|199|error: ‘::cosh’ has not been declared|
/usr/include/c++/7/cmath|218|error: ‘::exp’ has not been declared|
/usr/include/c++/7/cmath|237|error: ‘::fabs’ has not been declared|
/usr/include/c++/7/cmath|256|error: ‘::floor’ has not been declared|
/usr/include/c++/7/cmath|275|error: ‘::fmod’ has not been declared|
/usr/include/c++/7/cmath|296|error: ‘::frexp’ has not been declared|
/usr/include/c++/7/cmath|315|error: ‘::ldexp’ has not been declared|
/usr/include/c++/7/cmath|334|error: ‘::log’ has not been declared|
/usr/include/c++/7/cmath|353|error: ‘::log10’ has not been declared|
/usr/include/c++/7/cmath|372|error: ‘::modf’ has not been declared|
/usr/include/c++/7/cmath|384|error: ‘::pow’ has not been declared|
/usr/include/c++/7/cmath|421|error: ‘::sin’ has not been declared|
/usr/include/c++/7/cmath|440|error: ‘::sinh’ has not been declared|
/usr/include/c++/7/cmath|459|error: ‘::sqrt’ has not been declared|
/usr/include/c++/7/cmath|478|error: ‘::tan’ has not been declared|
/usr/include/c++/7/cmath|497|error: ‘::tanh’ has not been declared|
/usr/include/c++/7/cmath||In function ‘constexpr int std::fpclassify(float)’:|
/usr/include/c++/7/cmath|545|error: ‘FP_NAN’ was not declared in this scope|
/usr/include/c++/7/cmath|545|error: ‘FP_INFINITE’ was not declared in this scope|
/usr/include/c++/7/cmath|545|error: ‘FP_NORMAL’ was not declared in this scope|
/usr/include/c++/7/cmath|546|error: ‘FP_SUBNORMAL’ was not declared in this scope|
/usr/include/c++/7/cmath|546|error: ‘FP_ZERO’ was not declared in this scope|
/usr/include/c++/7/cmath|546|note: suggested alternative: ‘FD_ZERO’|
/usr/include/c++/7/cmath||In function ‘constexpr int std::fpclassify(double)’:|
/usr/include/c++/7/cmath|550|error: ‘FP_NAN’ was not declared in this scope|
/usr/include/c++/7/cmath|550|error: ‘FP_INFINITE’ was not declared in this scope|
/usr/include/c++/7/cmath|550|error: ‘FP_NORMAL’ was not declared in this scope|
/usr/include/c++/7/cmath|551|error: ‘FP_SUBNORMAL’ was not declared in this scope|
/usr/include/c++/7/cmath|551|error: ‘FP_ZERO’ was not declared in this scope|
/usr/include/c++/7/cmath|551|note: suggested alternative: ‘FD_ZERO’|
/usr/include/c++/7/cmath||In function ‘constexpr int std::fpclassify(long double)’:|
/usr/include/c++/7/cmath|555|error: ‘FP_NAN’ was not declared in this scope|
/usr/include/c++/7/cmath|555|error: ‘FP_INFINITE’ was not declared in this scope|
/usr/include/c++/7/cmath|555|error: ‘FP_NORMAL’ was not declared in this scope|
/usr/include/c++/7/cmath|556|error: ‘FP_SUBNORMAL’ was not declared in this scope|
/usr/include/c++/7/cmath|556|error: ‘FP_ZERO’ was not declared in this scope|
/usr/include/c++/7/cmath|556|note: suggested alternative: ‘FD_ZERO’|
/usr/include/c++/7/cmath||In function ‘constexpr typename __gnu_cxx::__enable_if<std::__is_integer<_Tp>::__value, int>::__type std::fpclassify(_Tp)’:|
/usr/include/c++/7/cmath|564|error: ‘FP_NORMAL’ was not declared in this scope|
/usr/include/c++/7/cmath|564|error: ‘FP_ZERO’ was not declared in this scope|
/usr/include/c++/7/cmath|564|note: suggested alternative: ‘FD_ZERO’|
/usr/include/c++/7/cmath|1080|error: ‘::double_t’ has not been declared|
/usr/include/c++/7/cmath|1081|error: ‘::float_t’ has not been declared|
/usr/include/c++/7/cmath|1084|error: ‘::acosh’ has not been declared|
/usr/include/c++/7/cmath|1085|error: ‘::acoshf’ has not been declared|
/usr/include/c++/7/cmath|1086|error: ‘::acoshl’ has not been declared|
/usr/include/c++/7/cmath|1088|error: ‘::asinh’ has not been declared|
/usr/include/c++/7/cmath|1089|error: ‘::asinhf’ has not been declared|
/usr/include/c++/7/cmath|1090|error: ‘::asinhl’ has not been declared|
/usr/include/c++/7/cmath|1092|error: ‘::atanh’ has not been declared|
/usr/include/c++/7/cmath|1093|error: ‘::atanhf’ has not been declared|
/usr/include/c++/7/cmath|1094|error: ‘::atanhl’ has not been declared|
||More errors follow but not being shown.|
||Edit the max errors limit in compiler options...|
||=== Build failed: 50 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

С абсолютным:

||=== Build: Debug in SDL (compiler: GNU GCC Compiler) ===|
/home/zues/Projects/code/SDL/MathHelper.h||In member function ‘float Vector2::Magnitude()’:|
/home/zues/Projects/code/SDL/MathHelper.h|23|error: ‘sqrt’ was not declared in this scope|
/home/zues/Projects/code/SDL/MathHelper.h|23|note: suggested alternative: ‘short’|
/home/zues/Projects/code/SDL/MathHelper.h||In function ‘Vector2 RotateVector(Vector2&, float)’:|
/home/zues/Projects/code/SDL/MathHelper.h|48|error: ‘cos’ was not declared in this scope|
/home/zues/Projects/code/SDL/MathHelper.h|48|error: ‘sin’ was not declared in this scope|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

1 ответ

Лучший ответ

Ошибки, которые вы видите, скорее всего, связаны с использованием зарезервированного имени:

#define _MATH_H

Который также используется glibc.

Правило состоит в том, чтобы не начинать имена с _ (правила более сложные, но они охватывают многое и их легко запомнить).


Кроме того, обратите внимание, что вместо:

#include </usr/include/math.h>

Чтобы включить библиотеку C math.h, вам нужно только включить:

#include <math.h>

Если вы хотите убедиться, что функции находятся в глобальном пространстве имен, или:

#include <cmath>

Если вы хотите убедиться, что они находятся в пространстве имен std (рекомендуется).


5

Acorn
18 Авг 2020 в 02:56

Arduino programming is an open-source and simple stage that arranges the Arduino board into working with a particular goal in mind. An Arduino code is written in C++ yet with extra capacities and strategies. An Arduino is an equipment and programming stage broadly utilised in hardware.

In this article, we go through three quick fixes for the error ‘was not declared in this scope’.

Also read: How to solve the Tower of Hanoi problem using Python?


What does the error mean?

Every programming language has a concept of Scope. Scope tells us where a specific variable, constant or function is accessible and usable. It refers to the area of code a statement, block, or name. The scope of an entity determines where that entity is usable in other parts of the program. The scope of a block determines where that block can be used in other blocks, and the scope of a name determines where that name can be used in other names.

There are two types of scope in programming languages: local and global. Local scope refers to the identifiers and symbols visible inside a block of code. Global scope, on the other hand, refers to the identifiers and symbols visible outside a block of code.

The error ‘was not declared in this scope’ generally occurs when a variable or function is not accessible to its call. A global variable in Arduino is the variable that is declared outside any function, including the setup() and loop() functions. Any variable declared inside a function or loop has restrictive access and is a local variable.

If any other function calls a local variable, it gives an error. To call any variable or function in any other function, including the setup() and loop() function, it should be declared as a global variable.

Also read: How to stop an Arduino program?


There are the quick fixes for the Arduino error: was not declared in the scope.

Declare the variable

Before assigning a value to the variable, make sure to define it. There are 16 data types commonly used in Arduino coding. Each data type expresses the nature of the value assigned to it. If the data type and value doesn’t match, an error arises. Also, if a variable is assigned any value without its declaration or data type, the error occurs.

Always ensure to declare the variable before the assignment. There are two ways to do this.

How to solve Arduino error: 'was not declared in this scope'?

There are three variables in the above example – num1, num2 and num3. The variable num1 has been declared separately and assigned to a data type corresponding value in the loop. The variable num2 has been declared and assigned in the same line of code. The variable num3, on the other hand, has directly been assigned a value without its declaration. This causes the error, as shown above.


Other details

There may be errors arising even after proper declaration and assignment of the variable. This may be due to incorrect or absence of the closing brackets, semicolons or improper declaration of functions. Ensure proper use of syntax when defining loops and functions. Every opening in curly brace must be accounted for and closed. Extra closing braces also cause errors. Alongside, semicolons hold their importance. A semicolon missed can cause the entire program to go haywire.


Library folder

Many times, variables call or use functions that require importing a few specific libraries.

How to solve Arduino error: 'was not declared in this scope'?

In the example above, the variable num calls the square root function – sqrt() from the maths library of Arduino. If we call a function without including its library first, an error occurs. There are multiple inbuilt and standard libraries in Arduino, while a few special libraries must be included separately.

Also read: What is ‘does not name a type’ in Arduino: 2 Fixes.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error simulator limit
  • Error ts2554 expected 0 arguments but got 1
  • Error simulator 861 failed to link the design
  • Error trying to find the directory for the game config file nfs most wanted 2012
  • Error ts2531 object is possibly null

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии