This question already has answers here:
Why should I not #include <bits/stdc++.h>?
(9 answers)
Closed 6 years ago.
I was creating a basic tic tac toe game on c++,I got the desired game output without including bits/stdc++ header file,but when included there was an ambiguity for global variable count(which is in use in the below mentioned code). Please explain!
#include <iostream>
#include "unistd.h"
#include <cstdlib>
#include<bits/stdc++.h>
using namespace std;
char a[3][3];
int count=0;
char player_flag ='X';
void init()
{
a[0][0]='1';
a[0][1]='2';
a[0][2]='3';
a[1][0]='4';
a[1][1]='5';
a[1][2]='6';
a[2][0]='7';
a[2][1]='8';
a[2][2]='9';
}
void show()
{
for(int i=0;i<3;i++)
{ for(int j=0;j<3;j++) cout<<a[i][j] << " " ;
cout << "\n" ;
}}
void entry(int n,char player_flag)
{
for(int i=0;i<3;i++)
{ for(int j=0;j<3;j++)
{ if(n==(i*3+j+1))
{if(a[i][j]=='X'||a[i][j]=='O')
{ int n;
cout<<"invalid entry enter another position\n";
cin>>n; entry(n,player_flag);
}
else a[i][j]=player_flag;
}}}}
void turn()
{
if(player_flag=='X') player_flag='O';
else player_flag ='X';
}
void check()
{ int i,j;
for(i=0,j=0;j<3;i=0,j++)
{if(a[i][j]==a[i+1][j]&&a[i+1][j]==a[i+2][j]) {cout<<"\n"<<a[i][j]<<" wins \n"; exit(0);}}
for(i=0,j=0;i<3;j=0,i++)
{if(a[i][j]==a[i][j+1]&&a[i][j+1]==a[i][j+2]) {cout<<"\n"<<a[i][j]<<" wins \n"; exit(0);}}
if(a[0][0]==a[1][1]&&a[1][1]==a[2][2])
{cout<<"\n"<<a[0][0]<<" wins";exit(0);}
else if(a[0][2]==a[1][1]&&a[1][1]==a[2][0])
{cout<<"\n"<<a[0][2]<<" wins";exit(0);}
else if(count>=9){ cout<<"\nits a draw\n"; exit(0);}}
int main()
{ init(); show();
while(1)
{ int n; count++;
cout<<"player "<<player_flag<<" turn: enter position to put \n"; cin>>n;
entry(n,player_flag);
system("clear");
show();
check();
turn();`
}}
error: reference to ‘count’ is ambiguous
else if(count>=9){ cout<<"\nits a draw\n"; exit(0);}}
This is one of many ambiguous count errors.
PS: if bits/stdc++ is not included then its works fine,error pops out only when bits/stdc++ is used. Any reply is encouraged, Thanks!
std::count is a function from the standard library.
http://www.cplusplus.com/reference/algorithm/count/
Since you use the namespace std , "count" can refer to either std::count or the variable count.
You need to either rename your variable, or stop using the std namespace.
You can also include only the c++ headers that you need instead of bits/stdc++.h which includes all of them.
I suspect count is in std namespace somewhere.
Remove the line
using namespace std;
Use the namespace specifier std:: wherever you need it explicitly.
You should not use
#include<bits/stdc++.h>
anyway. Use headers that are part of the standard.
PS
From the answer by #CFrugal:
std::count is a function from the standard library.
http://www.cplusplus.com/reference/algorithm/count/
The files in the bits/ directory are implementation details not to be included in your programs directly. They are included indirectly by the normal includes like <vector> and <iostream>. Since it's an implementation detail, it's allow to make assumptions about the context in which it's included and presumably your include location violates one of those assumptions.
Just include the normal standard header for the functionality you need instead of a bits file.
Upon reading your question a second time it looks like you may also have a second problem: using namespace std bringing the std::count function into the global namespace, which collides with your global int count. To fix this consider using specific functions from standard instead of the entire namespace (using std::cout;), or rename your count variable, or don't declare it at global scope.
Related
Actually this code works fine in "DEV C++", but when I put it into my "Hacker-Rank" panel it gives this error "reference to function is ambiguous", although all the online compilers are giving errors...
I don't think here function overloading is somewhere interrupting, because this error mostly comes in function overloading.
#include <bits/stdc++.h>
#include <cstdio>
#include<iostream>
using namespace std;
int function(int n);
int main()
{
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if(n<=0){
return(0);
}
else{
function(n);
}
}
int function(int n)
{
if (n<=9)
{
cout<<"experiment";
}
else{
cout<<"Greater than 9";
}
return 0;
}
The error with clang is:
<source>:20:9: error: reference to 'function' is ambiguous
function(n);
^
<source>:8:5: note: candidate found by name lookup is 'function'
int function(int n);
^
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/11.0.0/../../../../include/c++/11.0.0/bits/std_function.h:111:11: note: candidate found by name lookup is 'std::function'
class function;
^
// ... and more ....
For starters this else code block
else{
function(n);
}
returns nothing.
Though it is allowed but confuses readers of the program because they expect that if there is an explicit return statement in the if sub-statement then a similar return statement should be in the else sub-statement.
It seems the name function declared in the global name space conflicts with the standard name std::function due to the using directive.
using namespace std;
Write
else{
return ::function(n);
}
The problem is caused by #include <bits/stdc++.h> combined with the directive using namespace std.
<bits/stdc++.h> includes most (all, depending on the age of the version you have with your compiler) headers related to the C++ standard library.
One of the headers included by <bits/stdc++.h> (since C++11) is <functional>, which declares a templated class std::function. std::function has a templated constructor that can accept a single argument of any type.
In your main(), anything declared (visible to the compiler) named function is a candidate for being used by the statement function(n). The directive using namespace std tells the compiler to consider names within std as candidates. According to rules of the language, both your declared function() and std::function are equally good matches for the name function.
The real fix has two parts. The first is to avoid using headers like <bits/stdc++.h> and, instead, only include standard headers that are actually needed by your program.
The second part is to avoid using the directive using namespace std excessively, or even at all. It can cause names (of types, functions, variables, etc) within standard headers to accidentally match names in your code.
If you do a search, you will find plenty of explanations of why to avoid both <bits/stdc++.h> and to avoid using namespace std (or other using directives). Both have their uses, but both introduce hard-to-avoid gotchas (such as you have experienced).
Vlad has shown that working around the problems caused by using namespace std; can solve your problem. That is a good answer.
Funnily, you can also fix your problem by not applying the antipattern #include <bits/stdc++.h>. Even without Vlads proposed improvement.
#include <limits>
#include <cstdio>
#include<iostream>
using namespace std;
int function(int n);
int main()
{
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if(n<=0){
return(0);
}
else{
function(n);
}
}
int function(int n)
{
if (n<=9)
{
cout<<"experiment";
}
else{
cout<<"Greater than 9";
}
return 0;
}
More info on why I dare to describe that as "antipattern" is here:
Why should I not #include <bits/stdc++.h>?
#include<bits/stdc++.h>
using namespace std;
int count;
int main()
{
int k;
cin>>k;
count=k;
cout<<count;
return 0;
}
I am trying to change the value of 'count' (Global Variable) in main function but getting reference to 'count' is ambigous error in C++. But the same kind of code works well in C. Please help me.
Remove the using namespace std; line, add the std:: to cin and cout and it should be ok.
You have this compiler error because std::count exist: https://en.cppreference.com/w/cpp/algorithm/count
So it's ambigous for the compiler between std::count and your variable count because you use using namespace std.
When i want to compile a code, is giving me an error... cout and cin was not declared in this scope. What's the problem?
I searched on google. They said i need to reinstall codeblocks. I have done this and is not working.
#include <iostream>
int main()
{
int n,z,c;
cin>>n;
z=0;
while(n>0)
{
c=n%10;
n=n/10;
if(c<5)
{
z=z*10+2*c;
}
}
cout << z;
return 0;
}
It should compile it...
Just add this using namespace std; after #include <iostream> . Or use std::cin std::cout.
Also posting the 3rd way (compromise between the 2 existing answers - was already mentioned in the comments), which I think works best for the current scenario. This is my favorite one (well, excepting cases when I use lots of stuff from a namespace).
Add:
using std::cin;
using std::cout;
after the #include. This way:
You avoid using namespace X; hell. That's a big NO-NO, there are lots of resources explaining why (you could check [SO]: what is the reason for using a wildcard import? (#CristiFati's answer) for an equivalent in Python)
You don't have to type the fully qualified name every time (just the plain name). Using FQNs can be / is:
Very annoying (especially when dealing with nested namespaces)
Safe
Easier to read
Addding std::cin or std::cout would fix it
If you don't want to add std:: again and again then
You can also add using namespace std; just after #include<iostream>
This happens because cin and cout are members of standard library.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have searched this question in Google. I found some related question in stackoverflow.com and quora.com but i am still not clear about this two topics. Everyone says that we use #include<iostream> for input/output operation. Now, we take input using cin and print output using cout that means this two should be defined in #include<iostream>. But without using using namespace stdwe still can't take any input nor can print something on console. So, my questions are-
Where is cin and cout actually declared and defined? Is it in #include<iostream>or in namespace std?
If in #include<iostream>why should we use using namespace std?
If in namespace std why should we use #include<iostream?
After reading some article on the web and watching some videos on YouTube, I'm assuming cout and cin is defined in namespace std and the namespace std doesn't make any sense alone because it is defined in #include<iostream>. That's why we need to use them both. (Just my thought let me know if I am right or not.)
The purpose of this question is to be clear about this two facts. If you can help it would be great.
cin and cout are defined in the header iostream and in the namespace std. These concepts are orthogonal. iostream is a file name and std is a namespace used by the source code of that file.
As a way of keeping things organized, c++ provides namespaces. All of the standard library is defined within the namespace called std. Other libraries you might write or include may use their own namespace. For example, you might include a physics library in your project which wants to define the concept of algebraic vectors. By using it's own namespace (let's called if physlib) it can differentiate between it's vector (physlib::vector) and the standard vector (std::vector). Namespaces can also be nested to help organize large projects. For example, time keeping parts of the standard library are in std::chrono and file system related components are in std::filesystem.
The preferred way of using cin and cout is as following. :
#include <iostream>
int main()
{
std::cout << "Hello, World!\n";
return 0;
}
The statement using namespace std is simply an instruction to look in the namespace std by default. It allows you to omit the std:: part of using standard library components. It's generally regarded as a bad idea to used using namespace std.
Why should we use #include <iostream>
To bring the standard library's I/O functionality into our program.
while we are using using namespace std?
This allows us to use that functionality without writing std:: each time we do.
This is unrelated to the previous step. Writing only using namespace std does not bring I/O functionality into your program, and writing only #include <iostream> does not allow us to use that functionality without writing its components' names out in full (including the std:: prefix).
The #include directive determines what we can use;
The using namespace declaration determines how we can use it.
Perfectly fine:
#include <iostream>
int main()
{
std::cout << "Hello world!\n";
}
Also valid:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!\n";
}
Not valid:
int main()
{
std::cout << "Hello world!\n";
}
And neither is this:
using namespace std;
int main()
{
std::cout << "Hello world!\n";
}
or this:
using namespace std;
int main()
{
cout << "Hello world!\n";
}
#include <iostrem> tells the compiler to pull in the contents of the header iostream. That header provides, among other things, declarations of the objects std::cin and std::cout. So the basic "Hello, world" program looks like this:
#include <iostream>
int main() {
std::cout << "Hello, world\n";
return 0;
}
Similarly, if you want to use std::vector, you tell the compiler about it with #include <vector>. Same thing for the rest of the standard library: whatever it is that you want to use, find out which header declares it and #include that header.
using namespace std; doesn't define any names for you. It tells the compiler to pretend that any names that have been defined in the namespace std are also defined in the scope where using namespace std; occurs. So that means that instead of writing std::cout you can write cout, and the compiler will figure out that you meant std::cout. Unless, of course, you've written something yourself with the name cout (or any other name that's in std and declared in a header that you've #included), in which case that using declaration makes the use of the name ambiguous. There is no good reason to write using namespace std;. Just use the right names for things: std::cout is clear and unambiguous.
Where is cin and cout actually declared and defined? Is it in #include<iostream> or in namespace std?
It's not or. cin and cout are declared in the iostream header file within the namespace std.
If in #include< iostream> why should we use using namespace std?
You shouldn't. Either fully qualify the global variables like std::cin or std::cout. There's a number of reasons why you shouldn't use using namespace std; (at least in header files).
If in namespace std why should we use #include<iostream>?
Because you need the declarations to compile your code.
iostream is part of the standard library, here is what the "iostream.h" file would look like if you were to implement it yourself:
namespace std{
// code about cin
extern ostream cin;
// code about cout
extern ostream cout;
}
(see c++ STL cout source code)
Where is cin and cout actually declared and defined? Is it in #include <iostream> or in namespace std?
So cin/cout are declared and define in the standard library under the
namespace std. This means that if you want to use it in your code you can do :
int main()
{
std::cout << "Hello";
}
If in #include<iostream> why should we use using namespace std?
You don't need using namespace std, you could call std::cout everywhere instead of cout, but you can see how this can make your code verbose and annoying to type.
using namespace std in your whole file is actually discouraged as it could have unintended effect, usually you could use only
using std::cout;
using std::cin;
where needed.
The reason the using is needed (or the need for explicitly writing std:cout , is imagine you have the following code:
#include <iostream>
namespace mycoolnamespace
{
class foo {
public:
foo& operator<< (const std::string& echo)
{
// do stuff
}
};
foo cout; // created a variable called cout
}
int main()
{
cout << "Hello";
// ^^^^ compiler can't know if you meant to use std::cout or mycoolnamespace::cout here!
// Potential fix:
std::cout << "Hello"
}
If in namespace std why should we use #include<iostream>?
By default not all function/classes from the standard library are included in your program, otherwise a simple "Hello world" program would give a lot of work to the compiler since it would need to parse all the existing classes/functions in the entire standard library. #include<iostream> tells the compiler that you need the functions/classes available in the standard library's iostream 'file'
I am trying to create a lottery program within c++ and the issue i'm having is attempting to output all values of the Numbers array into a file, however when i run the code, the only thing that gets outputted is the first set of values i put in, however the program allows me to type in more than one set. (The program allows for up to 6 sets of data), however it only outputs one.
Here is all my code
LotteryData.cpp
LotteryData::LotteryData()
{
}
LotteryData::~LotteryData()
{
}
void LotteryData::PassInfo(int (&Numbers)[6][6], int &NumberofGames)
{
ofstream Numfile;
while(NumberofGames>0)
{
Numfile.open("Numbers.txt");
for (int j=0; j<6; j++)
{
Numfile << Numbers[NumberofGames][j];
}
NumberofGames = NumberofGames - 1;
Numfile.close();
}
}
Player.h
#pragma once
#include <iostream>
#include <fstream>
using namespace std;
class Player
{
private:
public:
Player();
~Player();
void Input();
int Numbers[6][6];
int NumberofGames;
};
main.cpp
#include <iostream>
#include "Lottery.h"
#include "Player.h"
#include "LotteryData.h"
using namespace std;
int main()
{
Player player;
Lottery random;
LotteryData data;
player.Input();
random.setRandomNumber();
data.PassInfo(player.Numbers, player.NumberofGames);
}
Im not exactly sure where the problem is coming from but i think it may be from one of the pointers although not entirely sure.
Any help on this problem would be much appreciated.
Cheers
Edit: I've Changed the code within the PassInfo function within LotteryData.cpp file as #ali suggested
Edit2: I've cut down on the code as to where I think the problem occurs but as all of the code compiles, Visual Studio 2012 doesnt point to any actual errors in the program
In the while loop in the PassInfo function you are not changing the value of NumberOfGames. Therefore in the for loop you are using the same row of your Numbers array. You need another for loop to change the index for the first index of the Numbers[][] array.