Меню

Using namespace std выдает ошибку

AKE

12 / 12 / 3

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

Сообщений: 384

1

14.05.2010, 00:16. Показов 28487. Ответов 17

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


C++
1
2
3
4
5
6
7
#include "stdio.h"
#include "string.h"
#include "math.h"
#include "stdlib.h"
#include "stdafx.h"
#include "iostream.h"
using namespace std; //здесь ошибка

error C2871: ‘std’ : does not exist or is not a namespace

Microsoft VC++ 6.0

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



0



бжни

2473 / 1684 / 135

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

Сообщений: 7,162

14.05.2010, 00:24

2

вы должные включить заголовки, которые чтонибудь туда добавят, например #include <vector> #include <iostream>



0



12 / 12 / 3

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

Сообщений: 384

14.05.2010, 00:27

 [ТС]

3

alex_x_x
А мне не нужно ничего туда добавлять…
Ошибка с потоковыми файлами…



0



229 / 67 / 11

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

Сообщений: 280

14.05.2010, 12:35

4

.h убери в iostream



0



Эксперт JavaЭксперт С++

8376 / 3598 / 419

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

Сообщений: 10,708

14.05.2010, 21:22

5

AKE, в зависимости от того как вы создавали проект, вам может не понадобится std;
MS VC++ 6 позволяет как использовать, так и не использовать std



0



Эксперт CАвтор FAQ

21259 / 8275 / 637

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

Сообщений: 22,634

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

15.05.2010, 08:47

6

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

error C2871: ‘std’ : does not exist or is not a namespace

namespace std появилось только в более поздних версиях стандарта Си++ и предназначен для того, чтобы втащить в него всё то, что описано в стандарте Си++ (чтобы проще было отделять мух от котлет). А в старых версиях стандарта (и, соответственно, в старых версиях компиляторах) этого namespace’а не было вообще.

К тому же раньше все заголовочные файлы от стандартных библиотек Си++ имели расширение .h: т.е. нужно было писать, например, #include <iostream.h>. В новых стандартах вся стандартная поддержка языка Си++ описана в заголовочных файлах без расширений: т.е. теперь надо писать #include <iostream>, но потом добавлять using namespace std; (либо ко всем глобалам обращаться через std, типа std::cout). Большинство современных компиляторов для совместимости поддерживают в том числе и старый вариант. Но в старых компиляторах нового варианта нет (потому что в те времена его ещё не изобрели).

Поэтому в твоём случае нужно просто удалить строку «using namespace std;» (поскольку ты использовал файл с расширением .h). Либо все подключаемые файлы стандартной библиотеки Си++ должны быть без .h (в твоём случае вместо iostream.h должно быть iostream)



2



-=ЮрА=-

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

Автор FAQ

05.01.2012, 23:17

7

Evg, чисто для себя хочу узнать — здесь на форуме часто вижу std::cout и т.д.(и все с пеной у рта утверждают что без std:: не по стандарту)
В случае если использую только функции std;(обычная консоль) логичней и лаконичней для кода записать using namespace std; под хедерами и не загромождать код std:: или я не прав???



0



Эксперт С++

3211 / 1459 / 73

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

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

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

05.01.2012, 23:37

8

-=ЮрА=-, раскрытие пространства имен, весьма опасная привычка. это годится для хеловордов, или же для программ не использующих ничего кроме стандартной библиотеки.



0



Эксперт CАвтор FAQ

21259 / 8275 / 637

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

Сообщений: 22,634

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

06.01.2012, 00:28

9

-=ЮрА=-, ну, например, ты можешь написать проект с 100500 функциями и называть их «a», «b», «c», … — это будет по стандарту, но затруднит тебе жизнь. С std:: то же самое. Если это «домашняя» программа на два экрана — то проще using использовать, в противном случае лучше std::. Да и вообще лучше заранее приучать себя к тому, что является «правильным» в случаях, когда большой проект пишут несколько людей



1



Gepar

1186 / 542 / 78

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

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

06.01.2012, 00:45

10

AKE, дело в том что написав
include «iostream.h» Вы уже подключили iostream с указанием что потоки cin, cout а также манипуляторы вроде endl принадлежат пространству имён std, тем не менее хотя строка

C++
1
using namespace std;

в вашем случае пользы не принесёт, проект и с ней должен нормально компилироваться, что и происходит в minigw, но почему-то не происходит в vs 6.0 (сам вот тоже проверил из интереса).
Но если подключить iostream в виде

C++
1
#include <iostream>

то тогда конфликтов у vs с пространствами имён не возникает так что либо пишите так либо не пишите using namespace std раз уж таким образом подключили нужные вам библиотеки.



0



Эксперт CАвтор FAQ

21259 / 8275 / 637

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

Сообщений: 22,634

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

06.01.2012, 01:01

11

Для полноты картину ещё и сюда ссылку закину: include <?> для cout



0



бжни

2473 / 1684 / 135

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

Сообщений: 7,162

09.01.2012, 14:52

12

вообще это вопрос холивара, а не языка



0



0 / 0 / 0

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

Сообщений: 38

11.11.2012, 23:38

13

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

-=ЮрА=-, ну, например, ты можешь написать проект с 100500 функциями и называть их «a», «b», «c», … — это будет по стандарту, но затруднит тебе жизнь. С std:: то же самое. Если это «домашняя» программа на два экрана — то проще using использовать, в противном случае лучше std::. Да и вообще лучше заранее приучать себя к тому, что является «правильным» в случаях, когда большой проект пишут несколько людей

Можно пример (желательно для новичка) в котором using namespace std; может повредить программе ?



0



бжни

2473 / 1684 / 135

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

Сообщений: 7,162

11.11.2012, 23:56

14

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

Можно пример (желательно для новичка) в котором using namespace std; может повредить программе ?

LinkedList list;



0



Croessmah

Don’t worry, be happy

17777 / 10542 / 2034

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

Сообщений: 26,510

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

12.11.2012, 00:01

15

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

может повредить программе ?

как вариант:

C++
1
2
3
4
5
6
7
8
9
10
#include <iostream>
 
using namespace std;
 
bool nothrow;
int main(){
    nothrow=true;
    std::cin.get();
    return 0;
}



0



0 / 0 / 0

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

Сообщений: 38

12.11.2012, 00:53

16

CroessmahПоясните, что здесь не верно ? К nothrow будет применяться std ?



0



424 / 389 / 113

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

Сообщений: 913

12.11.2012, 01:07

17

Переменная nothrow уже есть в std:: const std::nothrow_t std::nothrow
Наверно из-за этого будет конфликт.

Миниатюры

Возникает ошибка с using namespace std;
 



0



0 / 0 / 0

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

Сообщений: 38

12.11.2012, 01:10

18

Благодарю за пояснение.



0



  • Forum
  • General C++ Programming
  • error with using namespace std

error with using namespace std

the program runs well for this header file.
#pragma once
#include»birthday.h»
#include<string>
using namespace std;
class people
{
public:
people(string yourName, birthday DOB);
void printInfo();
private:
string name;
birthday dobObject;
};

but
by removing using namespace std; the programs fails with error. can you please give me the reason and elaborate?
#pragma once
#include»birthday.h»
#include<string>

class people
{
public:
people(string yourName, birthday DOB);
void printInfo();
private:
string name;
birthday dobObject;
};

Last edited on

1. Avoid

using namespace std;

at global scope in a header file.
2. In the header, use qualified names for entities from the standard library

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// #include guard
#include"birthday.h"
#include<string>

class people
{
    public:
        people( std::string yourName, birthday DOB );

        void printInfo() const ; // non-modifier, so const
    
    private:
        std::string name;
        birthday date_of_birth;	
};

#pragma once

class birthday
{
public:
birthday(int m, int d , int );
void printOutDOB();
private:
int day;
int month;
int year;

};

excuse me sir, but for above header file «bithday.h» i didn’t have to use qualified names for int. is there some rules for that in documentation or what? can you elaborate it?

1) Please use code tags when posting code, to make it readable:

http://www.cplusplus.com/articles/z13hAqkS/

2) There’s nothing in the header file that needs a std:: qualification, but there are things in your source file. Since there’s no longer a using namespace std; statement anywhere in the translation unit, you’ll need to qualify those names in the source file.

Last edited on

by removing using namespace std; the programs fails with error.

You do mean that the compiler aborts and gives error messages.

It is not enough to merely note that there is «an error». You have to read the error messages carefully, because they tell what offends the compiler.

For example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<string>

class people
{
    public:
        people( string yourName, int DOB );

        void printInfo() const ;
    
    private:
        string name;
        int date_of_birth;	
};

int main()
{
    return 0;
}

Produces on one compiler:

6:24: error: expected ')' before 'yourName'
11:9: error: 'string' does not name a type

and in another:

main.cpp:6:24: error: expected ')' before 'yourName'
         people( string yourName, int DOB );
                        ^
main.cpp:11:9: error: 'string' does not name a type
         string name;
         ^

Both clearly point to lines 6 and 11.

Line 11 is quite clear; the compiler understands that ‘string’ should probably be a name of a type, but compiler has not seen definition of such type. You do include <string> and it does contain definition of ‘string’, but that definition is within namespace ‘std’ and the compiler does not see inside namespaces unless it is told to look there.

Both using namespace std; and using std::string; essentially state that when looking for ‘string’, a ‘string’ inside ‘std’ is a match too.

std::string in code is more explicit: only the ‘string’ in ‘std’ is a match.

What is before ‘yourName’ on line 6? people( string
This message is harder to explain.
We can try to humor the compiler and test what happens if we write line 6 as:
people( string );
Alas, that gives a different error:

6:24: error: field 'string' has incomplete type 'people'

The important thing is to read those error messages and use the info the best you can.
For example, when asking for help do show the exact messages. Someone might be able to help you read them.

clang++ emits a very clear diagnostic.

MinGW64 6:38am /r/code/test >CC --version
clang version 5.0.1 (tags/RELEASE_501/final)
Target: x86_64-w64-windows-gnu
Thread model: posix
InstalledDir: C:msys64mingw64bin
MinGW64 6:38am /r/code/test >CC -c test.cpp
test.cpp:6:17: error: unknown type name 'string'; did you mean 'std::string'?
        people( string yourName, int DOB );
                ^~~~~~
                std::string
C:msys64mingw64includec++7.3.0bits/stringfwd.h:74:33: note: 'std::string' declared here
  typedef basic_string<char>    string;
                                ^
test.cpp:11:9: error: unknown type name 'string'; did you mean 'std::string'?
        string name;
        ^~~~~~
        std::string
C:msys64mingw64includec++7.3.0bits/stringfwd.h:74:33: note: 'std::string' declared here
  typedef basic_string<char>    string;
                                ^
2 errors generated.

Topic archived. No new replies allowed.

  • Remove From My Forums
  • Question

  • hi,

    i am writing a program containing serial port communication , for a customized hand held device, with the help of embedded VC++ 3.0. while compiling the module for the serial port , i am getting the following errors.

    error C2871: ‘std’ : does not exist or is not a namespace
    error C2065: ‘cout’ : undeclared identifier
    error C2297: ‘<<‘ : illegal, right operand has type ‘unsigned short [200]’

    my code contains the following lines…

    #include<iostream>
    #include «stdafx.h»
    #include «serial.h»

    #ifdef _DEBUG
    #define new DEBUG_NEW
    #undef THIS_FILE
    static char THIS_FILE[] = __FILE__;
    #endif
    using namespace std;
    HANDLE hCommPort = INVALID_HANDLE_VALUE;
    void CSerial::ConfigPort()
    {
    …..

    cout<< _T(«Com. port closed»)<<endl;
    ….
    ….
    kindly help me to solve this problem.

    thank you
    Geo Babu

Answers

  • Hi Geo,

    If you’re using precompiled headers the compiler will ignore anything above:

    Code Snippet

     #include «stdafx.h»

    You need to move your include to <iostream> below this line or put it inside stdafx.h.

    John.

Welcome to the boards. If you haven’t already done so then please take some time to familiarise yourself with the faq:
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Make sure you have a look at the the posting guidelines:
http://cboard.cprogramming.com/annou…ouncementid=51
Following the rules will ensure you get a prompt answer to your question.

Remember, too, that the board has a search facility, a link is at the top of your screen:
http://cboard.cprogramming.com/search.php
It will often get you a quicker answer to your questions than waiting for a response to one you have posted.

If you have any questions about this you may ask or you can contact one of our forum leaders:

http://cboard.cprogramming.com/showgroups.php

———————————————

In this case, it looks like you were able to search for a similar problem, but it would be better to start a new thread and link to the one you find rather than bumping the old thread.

Borland 5.02 appears to be a very old compiler that probably doesn’t support modern, standard C++ (and in this case namespaces). Consider using a different compiler. There are several free IDEs available that come with good modern compilers (e.g. VC++ Express, Dev-C++, Code::Blocks).

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    !
    Правила раздела Visual C++ / MFC / WTL (далее Раздела)

    >
    Компилятор не видит пространство имён std

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    13.04.10, 12:00

      переустанавливал windows => пришлось переустановить Visual Studio 2008 Express Edition.
      почему-то при любой попытке использовать std на этапе компиляции выдаёт ошибку

      Цитата

      error C2653: std: не является именем класса или пространства имен

      самое интересное, что когда в компиляторе ввожу std:: ,то вылазит окошечко со всем содержимым namespace’a.

      ExpandedWrap disabled

        std::wstring str1;

        class blalabadsf

        {

        private:    std::wstring str2;

        public: blalabadsf(void);

        };

        #include <string>

        using namespace std;

        wstring bla;

      ничего не срабатывает. может компилятор не настроен?

      Добавлено 13.04.10, 12:01
      и ещё, обычно же при записи std::string компилятор подсвечивает std, а сейчас нет..

      Сообщение отредактировано: Potroshitell — 13.04.10, 12:02


      AZote



      Сообщ.
      #2

      ,
      13.04.10, 12:28

        инклудишь стринги после определения класса? О_о

        ExpandedWrap disabled

          #include <string>

          using namespace std;

          wstring bla;

          std::wstring str1;

          class blalabadsf

          {

          private:    std::wstring str2;

          public: blalabadsf(void);

          };


        Potroshitell



        Сообщ.
        #3

        ,
        13.04.10, 12:40

          как-то странно.. компилятор то компилит файл с кодом, то не компилит его же… тут какая-то путаница, я пока попробую разобраться..

          Сообщение отредактировано: Potroshitell — 13.04.10, 12:49

          Guru

          Qraizer



          Сообщ.
          #4

          ,
          13.04.10, 12:48

            C или C++?


            Potroshitell



            Сообщ.
            #5

            ,
            13.04.10, 12:49

              с++

              Guru

              Qraizer



              Сообщ.
              #6

              ,
              13.04.10, 12:50

                А может вообще какой-нибудь CLI или C#?


                Potroshitell



                Сообщ.
                #7

                ,
                13.04.10, 12:50

                  нене, с++))


                  aster_x



                  Сообщ.
                  #8

                  ,
                  13.04.10, 13:36

                    Potroshitell
                    Тогда какие проблемы?

                    AZote тебе все правильно распсиал.

                    Сперва

                    ExpandedWrap disabled

                      #include <string>

                    потом юзаешь стринги.

                    0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                    0 пользователей:

                    • Предыдущая тема
                    • Visual C++ / MFC / WTL
                    • Следующая тема

                    Рейтинг@Mail.ru

                    [ Script execution time: 0,0296 ]   [ 16 queries used ]   [ Generated: 29.01.23, 02:55 GMT ]  

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

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

                    А вот еще интересные материалы:

                  • Яшка сломя голову остановился исправьте ошибки
                  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
                  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
                  • Using excel microsoft office interop excel ошибка
                  • Usflib dll ошибка ableton