Using namespace std ошибка

AKE

12 / 12 / 3

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

Сообщений: 384

1

14.05.2010, 00:16. Показов 30368. Ответов 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Эксперт С++

8384 / 3616 / 419

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

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

14.05.2010, 21:22

5

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



0



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

21274 / 8291 / 637

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

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

Записей в блоге: 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 / 74

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

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

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

05.01.2012, 23:37

8

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



0



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

21274 / 8291 / 637

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

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

Записей в блоге: 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

21274 / 8291 / 637

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

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

Записей в блоге: 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

Неэпический

17848 / 10616 / 2049

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

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

Записей в блоге: 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



Транслятор Borland C++ Builder 6.0.

Сижу тихо, пишу код:

using namespace std;

#include <stdio.h>

#pragma argsused
int main(int argc, char* argv[]){
return 0;
}

при трансляции в строке

using namespace std; 

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

[C++ Error] Unit1.cpp(2): E2282 Namespace name expected

если переставить первые две строки местами вот так:

#include <stdio.h>

using namespace std;

#pragma argsused
int main(int argc, char* argv[]){
return 0;
}

то все транслируется.

Почему ругается на объявление пространства имен?

aleksandr barakin's user avatar

задан 10 окт 2015 в 15:46

pepsicoca1's user avatar

pepsicoca1pepsicoca1

4,9991 золотой знак14 серебряных знаков27 бронзовых знаков

11

Причина ошибки заключается в том, что данный компилятор проверяет имя, используемое в директиве using: определено оно или нет.

Когда перед директивой включен заголовок, то, похоже этот заголовок определяет имя std, например, следующим образом

#if defined( __cplusplus )
namespace std
{

и поэтому директива, следующая после заголовка, может на него ссылаться.

Когда же заголовок не включен, то получается, что имя std не определено, и использование его в using директиве компилятор рассматривает как ошибку.

ответ дан 10 окт 2015 в 17:11

Vlad from Moscow's user avatar

Vlad from MoscowVlad from Moscow

44.7k3 золотых знака38 серебряных знаков89 бронзовых знаков

6

Прошу прощения, не только я запнулся на пространстве имён С++, поэтому разрешите предоставить объяснение Герберта Шилдта в книге «С++. Руководство для начинающих»: Приложение Б. Использование устаревшего С++ компилятора. При использовании современного компилятора у вас не должно быть проблем с компиляцией программ из этой книги. В этом случае вам вообще не понадобится информация, представленная в настоящем приложении. Как разъяснялось выше, программы, приведенные в этой книге, полностью соответствуют стандарту ANSI/ IS0 для С++ и могут быть скомпилированы практически любым современным С++-компилятором, включая Visual С++ (Мiсrosoft) и С++ Builder (Borland). Но если вы используете компилятор, созданный несколько лет назад, то при попытке скомпилировать наши примеры он может выдать целый список ошибок, не распознав ряд новых С++-средств. И в этом случае не стоит волноваться. Для того чтобы эти программы заработали со старыми компиляторами, нужно внести в них небольшие изменения. Чаще всего старые и новые С++-программы отличаются использованием двух средств: заголовков и npoстранств имен.» Я ПОКОРОЧЕ ОПИШУ: Новая версия компилятора не требует указывать расширение имён файлов заголовков(.h), НО ОБЯЗАТЕЛЬНО требуется объявлять пространство имён std. ЕСЛИ У ВАС ПРИ КОМПИЛЯЦИИ возникают ошибки с указанием на эти строки, ЗНАЧИТ У ВАС СТАРАЯ ВЕРСИЯ КОМПИЛЯТОРА, и ему надо указывать так:

#include <iostream.h> // указываем расширение имени файла заголовков .h

// using namespace std; — исключаем строку, объявляющую область пространства имён языка С++, необходимых для новой версии языка и компилятора.

ответ дан 5 авг в 3:12

Александр's user avatar

  • 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:\msys64\mingw64\bin
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:\msys64\mingw64\include\c++\7.3.0\bits/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:\msys64\mingw64\include\c++\7.3.0\bits/stringfwd.h:74:33: note: 'std::string' declared here
  typedef basic_string<char>    string;
                                ^
2 errors generated.

Topic archived. No new replies allowed.

#include <iostream>
using namespace std;
int main(){
   cout << "hello world!";
}

then there is a chance that there appears to be «cout is ambigous error» in problems tab even though there is no error to be found whatsoever. It appears for every «cout» in the file. if you write std:: before the cout the error gets removed.

#include <iostream>
#include <fstream>
using namespace std; 
void swap(int *element1, int *element2){
    int tmp = *element1;
    *element1 = *element2;
    *element2 = tmp;
}
void quicksort(int *inputfield, int n){
    cout << "{\ninputfield: ";
    for(int i = 0;i<n;i++){
        cout << inputfield[i] << " ";
    }
    cout << "\n";
    if(n>2){
        //getting the pivot:
        int pivot;
        {
            double pivotaverage = (inputfield[0] + inputfield[n/2] + inputfield[n-1])/3; // average of those pivots
            double a,b,c;
            a = abs(inputfield[0] - pivotaverage);
            b = abs(inputfield[n/2] - pivotaverage);
            c = abs(inputfield[n-1] - pivotaverage);
            if(a<=b && a<=c)pivot = 0; // getting the closest to average
            else if(b<=a && b<=c)pivot = n/2; //getting the closest to average
            else pivot = n-1; // getting the closest to average
            cout << "pivot index: " << pivot << "\n}\n";
            cout << "pivot value: " << inputfield[pivot];
        }
        int i = 0;
        for(int j = 0;j<n;j++){
            if(j == pivot)continue;
            if(i == pivot)i++;
            else if(inputfield[j] > inputfield[pivot])continue;
            else if(inputfield[j] <= inputfield[pivot]){
                //swap inputfield[i] with inputfield[j]
                int tmp = inputfield[i];
                inputfield[i] = inputfield[j];
                inputfield[j] = tmp;
            }
        }
        if(pivot < i){
            //swap pivot with with inputfield[i]
            int tmp = inputfield[i];
            inputfield[i] = inputfield[pivot];
            inputfield[pivot] = tmp;
            quicksort(inputfield, i+1);
            quicksort(inputfield + (i + 1) + 1, (n-((i+1)+1)));//give a pointer to element after the one that is scanned = (i+1) and skip the pointer = +1; then the length is n-that thing
        }
        else if(pivot > i){
            //swap pivot with inputfield[i+1]
            int tmp = inputfield[i+1];
            inputfield[i+1] = inputfield[pivot];
            inputfield[pivot] = tmp;
            quicksort(inputfield, i+1);
            quicksort(inputfield + (i + 1) + 1, (n-((i+1)+1)));//give a pointer to element after the one that is scanned = (i+1) and skip the pointer = +1; then the length is n-that thing
        }
    }
    else if(n == 2 && inputfield[0] > inputfield[1]){ // this is just to faster things up when it gets to the end
        int tmp = inputfield[1]; //Swap
        inputfield[1] = inputfield[0];
        inputfield[0] = tmp;
    }
    //if n = 1 or n = 0 there are no changes needed
}
int main(){
    int *field;
    int n;
    ifstream theFile("input.txt");
    string line;
    if(theFile){
        getline(theFile, line);
        for(int i = 0;line[i] != '\0';i++){
            if(line[i]<58 && line[i]>47){
                n = n*10+(line[i]-48);
            }
        }
        bool negative = false;
        field = new int[n];
        for(int i = 0;i<n;i++){field[i] = 0;}
        int g = 0;
        getline(theFile, line);
        for(int i = 0;line[i] != '\0';i++){
            if(line[i] == '-'){
                negative = true;
                cout << "hey";
            }
            else if(line[i] < 58 && line[i] > 47){
                field[g] = field[g]*10+(line[i]-48);
            }
            else{
                if(negative)field[g] = 0 - field[g];
                negative = false;
                g++;
            }
        }
        if(negative)field[g] = 0 - field[g];
    }
    else return 1;
    cout << n << '\n';
    for(int i = 0;i<n;i++){
        cout << field[i] << " ";
    }
    cout << "\n\n";
    quicksort(field, n);
    cout << "\n";
    for(int i = 0;i<n;i++){
        cout << field[i] << " ";
    }
    delete [] field;
} 

Note: if you restart vs code or wait long enough (4minutes) and then edit — it mostly disapears.

I have tested this with only c++ extension v1.10.7 running and C++ extension pack v1.2.0 running.

I have faced this issue on a low-tier laptop which might be a bit slower than usual. Make sure to replicate on lower-end hardware


Recommended Answers

Shouldn’t use void main. getch() isn’t a great way of stopping the program. iostream.h is non-standard. use iostream:

#include <iostream>

using namespace std;

int main( void ) {

  std::cin.ignore();
  return 0;
}

Jump to Post

All 4 Replies

Member Avatar for twomers


Shouldn’t use void main. getch() isn’t a great way of stopping the program. iostream.h is non-standard. use iostream:

#include <iostream>

using namespace std;

int main( void ) {

  std::cin.ignore();
  return 0;
}

Member Avatar for Ancient Dragon


Ancient Dragon

5,243



Achieved Level 70



Team Colleague



Featured Poster



Hi guys,
i have one question, when i type
using namespace std;
at top of my program my compiler gives some error
especially syntax error!
my compiler is Borland C++ v.5
for example simple code:

When using the old headers with .h extension you don’t use «using namespace std». Check to see if your compiler supports the new headers without an extension and use those instead. The old files are out-of-date and will cause lots of other problems if you attempt to use current coding practices.

Member Avatar for daniweb2013


Shouldn’t use void main. getch() isn’t a great way of stopping the program. iostream.h is non-standard. use iostream:

#include <iostream>

using namespace std;

int main( void ) {

  std::cin.ignore();
  return 0;
}

Thanks, it works, but i dont understand part of your code!
std::cin.ignore()
why you use that?!
my compiler gives error on that line?!, is it for pausing the screen?!
Regards

Member Avatar for n.aggel


n.aggel

13



Posting Whiz in Training



When using the old headers with .h extension you don’t use «using namespace std». Check to see if your compiler supports the new headers without an extension and use those instead. The old files are out-of-date and will cause lots of other problems if you attempt to use current coding practices.

fzafarani here is some more info on the subject {i found it on the internet!}:

The use of namespace std for all identifiers of the C++ standard library was introduced during
the standardization process. This change is not backward compatible to old header files, in which identifiers of the C++ standard library are declared in the global scope.
In addition, some interfaces of classes changed during the standardization process (however, the goal was to stay backward compatible if possible). So, a new style for the names of standard header files was introduced. This allows vendors to stay backward compatible by providing the old header files.

i got the text from here


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Понравилась статья? Поделить с друзьями:
  • Using excel microsoft office interop excel ошибка
  • Utorrent тест скорости ошибка теста скорости
  • Vag ошибка 07960
  • Usflib dll ошибка ableton
  • Usf ошибка на частотнике schneider