Error no member named cout in namespace std

VsCode Version : 1.14.1 Extension Version:0.12.1 Os : Win10 64Bit gcc : Mingw64(5.3.0) c_cpp_properties.json my code error tip
  • VsCode Version: 1.23.1
  • Extension Version: 0.17.1
  • Os: Win10 Pro Education
  • Version: 1803
  • gcc : wsl ubuntu16.04(5.4)

I’ve followed instruction described in https://github.com/Microsoft/vscode-cpptools/blob/master/Documentation/LanguageServer/Windows%20Subsystem%20for%20Linux.md, however, the intellisense tool generate: namespace «std» has no member «cout». This issue also is presented with other members in headers I use in my project, e.g., namespace «omnetpp» has no member «simsignal_t»

c_cpp_properties.json

{
    "configurations": [
        {

            "name": "WSL",
            "intelliSenseMode": "clang-x64",
            "compilerPath": "/usr/bin/gcc",
            "includePath": [
                "${workspaceFolder}",
                "/mnt/c/Users/Geo/omnetpp-5.2/include",
                "/mnt/c/Users/Geo/omnetpp-5.2/include/omnetpp",
                "/mnt/c/Users/Geo/omnetpp-5.2/include/omnetpp/platdep",
                "/mnt/c/Users/Geo/omnetpp-5.2/include/platdep",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/cmdenv",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/common",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/envir",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/eventlog",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/layout",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/nedxml",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/qtenv",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/qtenv/osg",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/scave",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/sim",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/sim/netbuilder",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/sim/parsim",
                "/mnt/c/Users/Geo/omnetpp-5.2/src/tkenv",
                "/mnt/c/Users/Geo/inet/src",
                "/mnt/c/Users/Geo/inet/src/inet",
                "/mnt/c/Users/Geo/inet/src/inet/common",
                "/mnt/c/Users/Geo/inet/src/inet/common/geometry/common",
                "/mnt/c/Users/Geo/inet/src/inet/mobility/base",
                "/mnt/c/Users/Geo/inet/src/inet/mobility/contract",
                "/mnt/c/Users/Geo/inet/src/inet/mobility/single",
                "${workspaceRoot}/src",
                "${workspaceRoot}/src/base",
                "${workspaceRoot}/src/engine",
                "${workspaceRoot}/src/simple"
            ],
            "defines": [
            ],
            "browse": {
                "path": [
                    "${workspaceFolder}",
                    "/mnt/c/Users/Geo/omnetpp-5.2/include",
                    "/mnt/c/Users/Geo/omnetpp-5.2/src",
                    "/mnt/c/Users/Geo/inet/src",
                    "/mnt/c/Users/Geo/gsim/slaw/src"
        
                ],
                "limitSymbolsToIncludedHeaders": true,
                "databaseFilename": ""
            },
            "cStandard": "c11",
            "cppStandard": "c++17"
        }
    ],
    "version": 4
}
  • Forum
  • Beginners
  • error: no type named ‘cout’ in namespace

error: no type named ‘cout’ in namespace ‘std’

I must have introduced some error that I can’t pinpoint

been writing

using std::cout;

instead of using namespace;

but somehow i can’t compile this and I keep getting

error: no type named ‘cout’ in namespace ‘std’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <unordered_set>
#include <vector>

using std::cout;
using std::cin;
using std::endl;
using std::unordered_set;
using std::vector;


class Solution {
public:
    void printDuplicate (int arr[], int n) {
        unordered_set<int> intSet;
        unordered_set<int> duplicate;

        for(int i=0; i<n; i++){
            if (intSet.find(arr[i]) == intSet.end())
                intSet.insert(arr[i]);
            else
                duplicate.insert(arr[i]);
         }

    }
    cout << "Duplicate items are: ";
    unordered_set<int> :: iterator itr;

    for(itr = duplicate.begin(); itr != duplicate.end(); itr++)
        cout << *itr << " ";
    };



int main(){
    int arr[] = { 1,2,3,5,6,7,9,3,6};

    Solution test;

    int n = sizeof(arr) / sizeof(int);

    test.printDuplicate(arr, n);

    return 0;
}

Last edited on

and if i write the code as follows, there’s no compilation error.

i’m trying to figure out what I did wrongly with the code in the first post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <unordered_set>
#include <vector>

using std::cout;
using std::cin;
using std::endl;
using std::unordered_set;
using std::vector;

// Print duplicates in arr[0..n-1] using unordered_set
void printDuplicates(int arr[], int n)
{
    // declaring unordered sets for checking and storing
    // duplicates
    unordered_set<int> intSet;
    unordered_set<int> duplicate;

    // looping through array elements
    for (int i = 0; i < n; i++)
    {
        // if element is not there then insert that
        if (intSet.find(arr[i]) == intSet.end())
            intSet.insert(arr[i]);

            // if element is already there then insert into
            // duplicate set
        else
            duplicate.insert(arr[i]);
    }

    // printing the result
    cout << "Duplicate items are : ";
    unordered_set<int> :: iterator itr;

    // iterator itr loops from begin() till end()
    for (itr = duplicate.begin(); itr != duplicate.end(); itr++)
        cout << *itr << " ";
}

// Driver code
int main()
{
    int arr[] = {1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5};
    int n = sizeof(arr) / sizeof(int);

    printDuplicates(arr, n);
    return 0;
}

In the OP, L26 & L29-31 are not within the function definition. Hence errors.

thanks seeplus, now I see my mistake.

much appreciated.

Hi,

It might seem easier to put using std::cout; et al at the beginning of your files, there will come a point when you get tired of having lots of these in a file. It is annoying if you give part of your code to others, they discover it doesn’t compile because the offending using statements aren’t there. Then one has to go through and fix these issues. It is better to do the following and not create issues.

It’s probably better to just put std:: before each std thing. One gets used to it; it should also possible to setup keyboard shortcuts in your IDE. I gather these are the things that coding professionals do.

Edit

IIt should also be possible to setup the IDE editor to automatically do pairs of braces, parentheses etc. , so no more having code outside functions, classes etc.

Last edited on

There is a more efficient way to print duplicated numbers using a std::map:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <map>
#include <chrono>

using std::cout;
using std::cin;
using std::endl;
using std::unordered_set;
using std::vector;

template<class TimeUnit = std::chrono::milliseconds>
class Timer {
public:
	Timer()
	{
		m_start = std::chrono::steady_clock::now();
	}
	~Timer()
	{
		std::chrono::steady_clock::time_point stop = std::chrono::steady_clock::now();
		std::cout << "** Running time: " << std::chrono::duration_cast<TimeUnit>(stop - m_start).count();
	}
private:
	std::chrono::steady_clock::time_point m_start;

};

// Print duplicates in arr[0..n-1] using unordered_set
void printDuplicates(int arr[], int n)
{
  // declaring unordered sets for checking and storing
  // duplicates
  unordered_set<int> intSet;
  unordered_set<int> duplicate;

  // looping through array elements
  for (int i = 0; i < n; i++) {
    // if element is not there then insert that
    if (intSet.find(arr[i]) == intSet.end())
      intSet.insert(arr[i]);

    // if element is already there then insert into
    // duplicate set
    else
      duplicate.insert(arr[i]);
  }

  // printing the result
  //cout << "Duplicate items are : ";
  unordered_set<int> ::iterator itr;

  // iterator itr loops from begin() till end()
  for (itr = duplicate.begin(); itr != duplicate.end(); itr++)
    cout << *itr << " ";
}
// Print duplicates in arr[0..n-1] using std::map
// based on some code from SO

void print_duplicates(int arr[], int n)
{
  std::map<int, size_t> cntMap;
  for (int i = 0; i < n; ++i) 
    cntMap[arr[i]]++;
  for (const auto&[first,second] : cntMap)
    //cout << first << "-> " << second << "n";
    if (second > 1)
      cout << first << " ";
}

int main()
{
  int arr[] = { 1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5 };
  int n = sizeof(arr) / sizeof(int);
  {
    Timer<std::chrono::microseconds> t;
    printDuplicates(arr, n);
  }
  cout << " micros n";
  {
    Timer<std::chrono::microseconds> t;
    print_duplicates(arr, n);
  }
  cout << " micros n";
}

Output:

1 2 5 ** Running time: 755 micros
1 2 5 ** Running time: 298 micros
Press any key to close this window . . .

Last edited on

Well on my system I get (as x64):


1 2 5 ** Running time: 464 micros
1 2 5 ** Running time: 938 micros

…..

Very strange. I tried x64 on VS 2019 Release and the first version is even worse:

1 2 5 ** Running time: 1449 micros
1 2 5 ** Running time: 322 micros

Maybe later I have more time and can try https://quick-bench.com

Last edited on

I agree that from the code the second should be faster. Tried again:


1 2 5 ** Running time: 432 micros
1 2 5 ** Running time: 976 micros

maybe it’s something in the timing…

On MinGW with -O3 results are much more extreme:

5 1 2 ** Running time: 985 micros
1 2 5 ** Running time: 18 micros

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <vector>
#include <unordered_set>
#include <set>
#include <random>
#include <type_traits>
#include <chrono>
#include <ctime>
#include <string>

std::vector< std::uint_fast32_t > make_test_data( std::size_t n )
{
    static std::mt19937 rng( std::random_device{}() ) ;

    std::vector< std::uint_fast32_t > data;
    while( data.size() < n ) data.push_back( rng() ) ;
    return data ;
}

struct timer
{
    using clock_type = std::conditional< std::chrono::high_resolution_clock::is_steady,
                                         std::chrono::high_resolution_clock, std::chrono::steady_clock>::type ;


    explicit timer( std::string label = "" ) noexcept : label( std::move(label) ) {}
    ~timer()
    {
        const auto end_pc = std::clock() ;
        const auto end_wc = clock_type::now() ;
        const auto processor_millisecs = ( end_pc - start_pc ) * 1000.0 / CLOCKS_PER_SEC ;
        using namespace std::chrono ;
        const auto wall_clock_millisecs = duration_cast<milliseconds>( end_wc - start_wc ).count() ;
        std::cout << label << " : " << processor_millisecs << " millisecs processor, "
                  << wall_clock_millisecs << " millisecs wall clockn" ;
    }

    const clock_type::time_point start_wc = clock_type::now() ;
    const std::clock_t start_pc = std::clock() ;
    const std::string label ;
};

template < typename SET_TYPE > std::vector< std::uint_fast32_t > find_dups( const std::vector< std::uint_fast32_t >& data )
{
    SET_TYPE set ;
    std::vector< std::uint_fast32_t > dups ;
    for( auto v : data ) if( set.insert(v).second == false ) dups.push_back(v) ;
    return dups ;
}

int main()
{
    const std::size_t N = 2'000'000 ;
    const auto data = make_test_data(N) ;

    {
        timer t("using std::set") ;
        const auto dups = find_dups< std::set<std::uint_fast32_t> >(data) ;
        std::cout << "nfound " << dups.size() << " duplicate itemsn" ;
    }

    {
        timer t("using std::unordered_set") ;
        const auto dups = find_dups< std::unordered_set<std::uint_fast32_t> >(data) ;
        std::cout << "nfound " << dups.size() << " duplicate itemsn" ;
    }
}

On Coliru:

g++ -std=c++20 -O3 -Wall -Wextra -pedantic-errors main.cpp && ./a.out
echo ================================
clang++ -std=c++2a -O3 -Wall -Wextra -pedantic-errors main.cpp && ./a.out

found 471 duplicate items
using std::set : 2701.25 millisecs processor, 2701 millisecs wall clock

found 471 duplicate items
using std::unordered_set : 1249.6 millisecs processor, 1249 millisecs wall clock
================================

found 469 duplicate items
using std::set : 2578.7 millisecs processor, 2578 millisecs wall clock

found 469 duplicate items
using std::unordered_set : 1223.97 millisecs processor, 1223 millisecs wall clock

http://coliru.stacked-crooked.com/a/9d82db611cf15048

(Note that for unordered set, insertion would be expensive when rehashing is required.)

Topic archived. No new replies allowed.

  • Remove From My Forums
  • Question

  • #include<iostream>
    #include «stdafx.h»
    #include<string>
    using namespace std;
    #include<io.h>

    void search(string path,int layer)
    // path stands for the folder name; layer stands for the current level of file systems
    {
        struct _finddata_t filefind;
        string curr = path+»\*.*»;
        int done = 0, i, handle;

        if((handle=_findfirst(curr.c_str(),&filefind))==-1){
      return; // no file exist in the folder
     }

        while(!(done=_findnext(handle,&filefind)))
        {
            if(!strcmp(filefind.name,»..»))
       continue;

              for(i=0;i<layer;i++) cout<<»  «;

              if ((_A_SUBDIR==filefind.attrib)) // if it is a fodler
            {     
                std::cout<<filefind.name<<«(dir)»<<endl;
                curr=path+»\»+filefind.name;
                search(curr,layer+1);
            }
            else
            {
                cout<<filefind.name<<endl;
            }
        }   
        _findclose(handle);     
    }
    void main()
    {
        string path;
        cout<<«input folder name»<<endl;
        cin>>path;
        search(path,0);
    }
    // that’s the source code

    >—— Build started: Project: Gary2, Configuration: Debug Win32 ——
    1>Compiling…
    1>directory.cpp
    1>c:usersgarydocumentsvisual studio 2005projectsgary2gary2directory.cpp(17) : warning C4244: ‘=’ : conversion from ‘intptr_t’ to ‘int’, possible loss of data
    1>c:usersgarydocumentsvisual studio 2005projectsgary2gary2directory.cpp(26) : error C2065: ‘cout’ : undeclared identifier
    1>c:usersgarydocumentsvisual studio 2005projectsgary2gary2directory.cpp(30) : error C2039: ‘cout’ : is not a member of ‘std’
    1>c:usersgarydocumentsvisual studio 2005projectsgary2gary2directory.cpp(45) : error C2065: ‘cin’ : undeclared identifier

Answers

  • Thank you, I have already found the solution. The fatal error i made here is putting stdfax in the wrong position. I should put it in the front of iostream

    • Marked as answer by

      Thursday, December 17, 2009 7:13 AM

Dimedron

0 / 0 / 0

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

Сообщений: 1

1

06.06.2017, 21:00. Показов 34078. Ответов 1

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


Вот такие ошибки в общем

Ошибка namespace "std" не содержит члена "cout"

Собственно, вот сам код

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma once
 
#include <Windows.h>
#include <fstream>
#pragma warning(disable: 4996)
 
 
void LogicalDrive()
{
    FILE* file = fopen("C:\Users\GLaDOS\Documents\Visual Studio 2017\ProjectslogicalDisk.txt", "w");
    char buf[26];
    GetLogicalDriveStringsA(sizeof(buf), buf);
    char *DRF[] = { "Unknown" , "Invalid path", "Removable", "Fixed" , "Network drive","CD-ROM", "RAM disk" };
    for (char *s = buf; *s; s += strlen(s) + 1)
    {
        std::cout << s << "  " << DRF[GetDriveTypeA(s)] << std::endl;
        fputs(s, file);
        fputs(DRF[GetDriveTypeA(s)], file);
        fputs("n", file);
    }
    fclose(file);
}

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

06.06.2017, 21:00

Ответы с готовыми решениями:

error C2886: std::cout: использование символа в «using»-объявлении члена не допускается
подскажите плз что ето может бить…если не подключаю файл Nokia.h тогда всьо норм..
#include…

Где ошибка невозможно преобразовать указатель «this» из «const pers» в «pers &» при выводе объектов через cout
Добрый день!
Переписал код из книг Лафоре, создание мультимножества из собственных объектов-…

В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно»
В зависимости от времени года &quot;весна&quot;, &quot;лето&quot;, &quot;осень&quot;, &quot;зима&quot; определить погоду &quot;тепло&quot;,…

namespace «std» has no member «vector»
Собственно такая проблема, мне нужно использовать в программе std::vector, однако VC ругается, мол…

1

Contents

test local function definitions are illegal C++

Error C2660 : function does not take 3 arguments

Error LNK2019 unresolved external symbol

E0042 operand types are incompatible ( char and const char * )

E0025 quoted string should contain at least one character

error: ‘cout’ in namespace ‘std’ does not name a type

undefined reference to `std::cout’

Если начинается на C, то это ошибка компиллятора.

Если на L, то линкера.

test local function definitions are illegal C++

Появляется если Вы случайно определили функцию не перед main а внутри main.

Error C2660 : function does not take 3 arguments

Компилятор ждёт, что у функции будет другое количество аргументов.

Появляется, например, если Вы не подключили нужную функцию, но существует
функция перегрузка с другим количеством аргументов. Копилятор не находит
нужную функцию, находит ту у которой такое же название, пытается использовать,
но количество аргументов неправильно.

Error LNK2019 unresolved external symbol

Линкер видит, что вызывается функция, которая нигде не задана.

E0042 operand types are incompatible ( char and const char * )

Появляется обычно при сравнении char с символом в двойных кавычках.

Нужно заменить двойные кавычки одинарными

char s = line[0];

if (s == 'T') {
std::cout << "TopBicycle.ru" << std::endl;
}

E0025 quoted string should contain at least one character

Обычно появляется когда вы пытаетесь создать пустую строку но делаете это с одинарными кавычками.

Нужно заменить одинарные кавычки двойными.

empty_line = "";

‘cout’ in namespace ‘std’ does not name a type

error: ‘cout’ in namespace ‘std’ does not name a type

Скорее всего вы пытаетесь сделать вывод без функции

std::cout << «Hello»;

С++ на это ругается, поэтому нужно завернуть вывод в функцию

void log() {
std::cout << «Hello»;
}

undefined reference to `std::cout’

undefined reference to `std::cout’

Означает, что скорее всего вам нужен g++ а не gcc

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

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

  • Error no matching repo to modify powertools
  • Error no matching function for call to stoi int
  • Error no matching function for call to pow int
  • Error ntopng requires redis server to be up and running
  • Error no matching function for call to find

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

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