Cout is ambiguous c ошибка

This kind of thing doesn’t just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven’t done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I’d ask why you’re including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to «C++-ise» them. In theory, including both wouldn’t conflict but, well, this is Microsoft we’re talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can’t explain what’s going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don’t need to worry too much about this, but I can imagine the false positives being annoying when you’re working in your IDE.

  • Forum
  • General C++ Programming
  • Cout is ambiguous?

Cout is ambiguous?

What does that mean? How do I fix it?

Post the actual error message, as well as the line of code which is causing the error.

Post your code so that it is [code]between code tags[/code] as this will give it syntax highlighting and line numbers.

Please copy and paste the exact error message, and indicate which line the error is talking about.

Last edited on

Well, I am working on this bank database project and whenever I post this part:

void addaccount()
{
ifstream inData;
ofstream outData;
string fileName;
string str;
cout << «Insert the name of the data file: «;
cin >> fileName;
inData.open(fileName); // Access the file of the name you had inputted
string lastName, firstName, type;
double balance;
inData >> lastName >> firstName >> balance >> type;
cout << «What file would you like to save the data in?: «;
cin >> fileName;
outData.open(fileName);
outData << str;
cout << «nEnter the customer’s last name:»;
cin >> lastName;
cout << «nnEnter the customer’s first name : «;
cin >> firstName;
cin.ignore();
cin.getline(50, firstName);
cout << «nEnter Type of The account (C/S) : «;
cin >> type;
type = toupper(type);
cout << «nEnter The Initial amount(>=500 for Saving and >=1000 for current ) : «;
cin >> deposit;
cout << «nnnAccount Created.»;
}

void deleteaccount();
{
account ac;
ifstream inFile;
ofstream outFile;
inFile.open(«account.dat», ios::binary);
if (!inFile)
{
cout << «File could not be open !! Press any Key…»;
return;
}
outFile.open(«Temp.dat», ios::binary);
inFile.seekg(0, ios::beg);
while (inFile.read(reinterpret_cast<char *> (&ac), sizeof(account)))
{
if (ac.retacno() != n)
{
outFile.write(reinterpret_cast<char *> (&ac), sizeof(account));
}
}
inFile.close();
outFile.close();
remove(«account.txt»);
rename(«Temp.txt», «account.txt»);
cout << «nntRecord Deleted ..»;
}

void search();
{
int seqSearch(const int list[], int listLength, int searchItem)
{
int loc;
bool found = false;

for (loc = 0; loc < listLength; loc++)
if (list[loc] == searchItem)
{
found = true;
break;
}
if (found)
return loc;
else
return -1;
}

into it, all the couts get the error message IntelliSense: «cout» is ambiguous.

Speaking of which, I really need help with that. I have a topic called ‘Bank Database’ I could really use help with.

IntelliSense errors aren’t compilation errors. Sometimes IntelliSense can get confused or out of date.

Go to Build -> Rebuild

You may also consider trying to prefix your ‘cout’ object with its namespace, ‘std’. In other words, wherever you’ve put

cout << "Information";

You may consider putting

std::cout << "Information";

Perhaps there are multiple objects called ‘cout’ in your program (or you’ve included external libraries which also have a cout object) and providing a namespace might give some clarification as to which one you mean.

Topic archived. No new replies allowed.

The cout is ambiguous vscode mistake usually affects scripts and documents when no good string, or the declared variable called cout is unresponsive. As a result, your computer confirms the system is ambiguous C++ and blocks your project, although nothing looks wrong with the syntax.cout is ambiguous

Therefore, readers can explore this guide because it explains why the reference to variable is ambiguous C++ and how to debug it without causing further complications. Moreover, this article includes several chapters that reproduce the error and pinpoint how the reference to class is ambiguous C++, so keep reading for more.

Contents

  • Why the Cout Is Ambiguous? Causes Of The Problem
    • – The Couts and Cins Are Ambiguous
    • – Porting Functions From Java to C++
    • – The Full Invalid Message
  • The Cout Is Ambiguous Will Disappear: The Ultimate Solution
  • Conclusion

Why the Cout Is Ambiguous? Causes Of The Problem

The reference to max is ambiguous when your C++ document or function does not have a correct string or the declared variable called cout needs to be more responsive. Consequently, this forces the system and your project to fail, so developers must fix it to continue coding.

In addition, your program may state the fprintf is ambiguous due to an exact cause, which is the primary command in most advanced applications. This mistake also confirms that working in C++ is sometimes challenging, especially for less experienced developers because they face unexpected obstacles that ruin their programming experience. Although the cout C++ error is less typical with modern programs, our experts confirmed it affects Visual Studio 2013 IDE. Consequently, developers should locate the mistake and apply the most advanced debugging methods.

However, you must prepare to learn how to fix the error because you must discover the two possible culprits that launch this mistake in your document. In addition, the examples include complex commands and functions to prove no script is safe from this bug, no matter how long or short it is. So, let us discover the first cause that launches this mistake in the following chapter.

– The Couts and Cins Are Ambiguous

Our experts provide a detailed example that is incorrect because the couts and cins are ambiguous, which is confirmed by the invalid message. However, we will not include the complete syntax because our experts will focus on the elements and values that provoke this bug.

You can learn more about the incorrect syntax in the following example:

//—–MAIN MENU(BEGIN)—–

system(“CLS”);

if (Player.l_a == “Damaged”)

{

cout << “Your Left Arm is damaged! Sleep for a while to fix it!”;

Sleep(1600);

}

if (Player.r_a == “Damaged”)

{

cout << “Your Right Arm is damaged! Sleep for a while to fix it!”;

Sleep(1600);

}

if (Player.l_l == “Damaged”)

{

cout << “Your Left Leg is damaged! Sleep for a while to fix it!”;

Sleep(1600);

}

if (Player.r_l == “Damaged”)

{

cout << “Your Right Leg is damaged! Sleep for a while to fix it!”;

Sleep(1600);

}

if (Player.money >= 1000 && Player.rank == “Private 2”)

{

system(“CLS”);

cout << “You have been promoted to Private First Class!”;

Player.rank = “Private First Class”;

Sleep(1600);

}

if (mmenuch1 == 2)

{

system(“CLS”);

cout << “You sleep, restoring your energy.”;

Player.energy = 100;

if (Player.l_a == “Damaged”)

{

cout << “nnYour Left Arm was healed.”;

Player.l_a = “Normal”;

}

if (Player.l_l == “Damaged”)

{

cout << “nnYour Left Leg was healed.”;

Player.l_l = “Normal”;

}

if (Player.r_l == “Damaged”)

{

cout << “Your Right Leg was healed.”;

}

Unfortunately, there are other causes for this error, as you will learn in the following example.

– Porting Functions From Java to C++

Another typical culprit for this mistake is porting functions from Java to C++, which is easy. However, developers face some string obstacles because their script has a few invalid public classes. In addition, the values inside the types appear correct, which confuses developers.Cout Is Ambiguous Causes

Let us learn about this code in the following example:

#include <iostream>

#include <string>

using namespace std;

class Bank {

public:

Bank();

~Bank() {}

int addCred(int addCred) {

currCred += addCred;

totalCred += addCred;

return currCred;

}

int giveChange(int deductCred){

currCred -= deductCred;

totalCred -= deductCred;

return currCred;

}

void updateCred(int cred) { currCred = cred; }

int getCred() { return currCred; }

private:

int currCred;

int totalCred;

};

Bank::Bank() {

currCred = 0;

totalCred = 2000;

}

class Display {

public:

Display();

~Display() {}

void showDisplay(string displayText) {

text = displayText;

cout<<“DISPLAY:: ” <<text;

}

void clear() {

text = “READY”;

showDisplay(text);

}

private:

string text;

};

Keypad::Keypad() {}

class Product{

public:

Product(const char* itsName = “”, int itsPrice = 0):

name(itsName), price(0)

{}

// normal constructor

Product(const string& itsName, int itsPrice):

name(itsName), price(itsPrice) {}

const string& getName() const {return name;}

int getPrice() const {return price;}

private:

string name;

int price;

};

void main() {

//Create objects needed

Tray* tList = tray_prod_init();

Bank* moneyBag = new Bank();

Display* display = new Display();

Keypad* keypad = new Keypad();

}

As you can tell, both examples have many values and launch the mistake. Therefore, before learning the solutions, let us learn about the exception message.

– The Full Invalid Message

Invalid messages and exceptions usually contain more code lines that pinpoint the exact cause and help developers debug the syntax. As a result, we included this section before the solution chapters to help you understand where and why the code fails. First, we will provide the exception from the previous example.

The following example includes the incorrect warning:

C2872: ‘cout’ : ambiguous symbol

C2679: binary ‘<<‘ : no operator defined which takes a right-hand operand of type ‘class std::basic_string<char,struct std::char_traits<char>,class std::allocator

<char> >’ (or there is no acceptable conversion)

This code confirms the affected code lines and why the binary values fail. Consequently, programmers and developers can use this message to pinpoint invalid processes and apply the solution. So, let us discover the best solution for this error in the following chapter. It is full-proof and will not mess up other functions and commands in your code.

The Cout Is Ambiguous Will Disappear: The Ultimate Solution

Removing the included string from your document is the best way to remove this error from your program. For instance, according to our experience, deleting the std library because some values might act as false positives, especially when working with IDE.



This procedure debugs the program because a fully functional document can only have a single std library, although a C header has the same purpose. Fortunately, developers can remove another command to debug the script.

Namely, your primary document must never have two variables with identical names maintained by the for a loop. So, deleting this variable from the second instance will make you forget about the mistake. But how does this look in practice?

The following example explains two incorrect variables:

int i; // incrementor in for loop

while ( … ) {

if ( … ) {

for (int i = 1; i <= 3; i++) {

}

if (i == 4) {

As you can see, we omitted the unnecessary values and properties so that we could focus on the variable on the first and sixth code lines. Now, delete the int command from the sixth line, as shown here:Removing the included string

int i; // incrementor in for loop

while ( … ) {

if ( … ) {

for (i = 1; i <= 3; i++) {

}

if (i == 4) {

This is the easiest way to debug your syntax because your code does not have complex changes or code alterations.

Conclusion

The reference to a variable is ambiguous when your C++ document or function does not have a correct string or the declared variable called cout is unresponsive. Henceforth, deleting some commands is vital to enable your program, as explained and summarized in the following bullet list:

  • Pinpointing the ambiguous error in your code is challenging because the script looks full-proof and functional
  • Although this bug does not affect modern programs and applications, our experts confirmed it with Visual Studio 2013 IDE
  • The bug affects your couts and cins, as explained in this article’s introductory example code
  • Although porting functions from Java to C++ is easy, the program may launch this mistake due to invalid values
  • The solutions are simple and require deleting some commands, such as the include std string or the second variable

The unexpected ambiguous cout error should not discourage beginners as the solutions are easy to implement. So, gear up and start scanning your code and delete the variables that confuse the processes.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Hi! I’m currently taking an introduction to C++ course and we just learned about for loops and how to use them. As practice, I took an example program I wrote when learning about counter-controlled loops and rewrote it to use a for loop statement instead of a while loop statement.

Unexpectedly, it started giving me the error ‘cout is ambiguous,’ which I haven’t seen for nor does looking it up tell me why this is happening in my case. The program still works when running it though, so I’m not entirely worried, but I would like to know why it’s popping up when all I did was change the kind of loop statement it’s in.

I’m using Visual Studio 2019 Community as my compiler

Code: https://ideone.com/kYVmAG

What’s more strange is that I did rewrite the program in a separate solution file and it didn’t give me ‘cout is ambiguous’ then, which makes me want to know why it’s giving me this error now even more.

Я не знаком с шаблонами. Я только начал изучать это. Почему я получаю ошибки в следующей программе?

#include <iostream>
#include <string>
using std::cout;
using std::string;
template<class C>
C min(C a,C b) {
return a<b?a:b;
}
int main()
{
string a="first string";
string b="second string";
cout<<"minimum string is: "<<min(a,b)<<'n';
int c=3,d=5;
cout<<"minimum number is: "<<min(c,d)<<'n';
double e{3.3},f{6.6};
cout<<"minimum number is: "<<min(e,f)<<'n';
char g{'a'},h{'b'};
cout<<"minimum number is: "<<min(g,h)<<'n';
return 0;
}

Ошибки:

13  [Error] call of overloaded 'min(std::string&, std::string&)' is ambiguous

6   [Note] C min(C, C) [with C = std::basic_string<char>]

Пожалуйста, помогите мне.

11

Решение

Здесь происходит две вещи.

Ваша первая проблема заключается в том, что вы включили только часть сообщения об ошибке. Вот ссылка на код, выполняемый в gcc и clang, и одно из полученных сообщений об ошибке (полностью):

main.cpp:13:34: error: call to 'min' is ambiguous
cout<<"minimum string is: "<<min(a,b)<<'n';
^~~
/usr/include/c++/v1/algorithm:2579:1: note: candidate function [with _Tp = std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >]
min(const _Tp& __a, const _Tp& __b)
^
main.cpp:6:3: note: candidate function [with C = std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >]
C min(C a,C b) {
^

Есть два кандидата. Один в main.cpp:6:3 (строка 6, символ 3) и один на algorithm:2579:1 (строка 2579, символ 1).

Один из них ты написал, а один из них в #include <algorithm>,

Один из ваших заголовочных файлов включен <algorithm> без тебя об этом. Стандартные заголовки могут делать это, как бы это ни раздражало.

В <algorithm> Eсть std::min шаблон функции. Как std::string это экземпляр класса шаблона в namespace std, шаблон функции std::min обнаруживается с помощью процесса, называемого «поиск с учетом аргументов» или «поиск по Кенигу». (Кандидаты перегрузки функции ищутся локально, а также в пространствах имен аргументов функции, а также в пространствах имен аргументов шаблона для аргументов функции и в пространствах имен вещей, на которые указывают аргументы объекта. функция и т. д.)

Ваша местная функция min также находится в том же пространстве имен, что и тело main,

Оба одинаково хороши, и компилятор не может решить, какой из них вы хотите вызвать. Так что выдает ошибку, сообщающую вам об этом.

И gcc и clang делают error: затем последовательность note:s. Обычно все из note:s после ошибки важны для понимания ошибки.

Чтобы это исправить, попробуйте позвонить ::min (полностью квалифицируя вызов), или переименовав функцию во что-то другое, или сделайте вашу версию более подходящей, чем std::min (сложно, но выполнимо в некоторых случаях), или вызов (min)(a,b), Последний блокирует поиск ADL / Koenig, а также блокирует раскрытие макроса (например, если какая-то ОС вставила #define min макросы в их системные заголовки) (через @ 0x499602D2).

14

Другие решения

Вы столкнулись с именным столкновением с std::min, Скорее всего, он включен в один из других стандартных заголовков библиотеки, которые вы включили, либо <iostream> или же <string>моё предположение, вероятно, последнее. Быстрое решение состоит в том, чтобы переименовать вашу функцию. Например, переименовав его в mymin работает отлично. демонстрация

5

Программа по вычислениям полностью устраивает, она перемножает 2 матрицы указанного размера с рандомными числами, она запускается и правильно считает, но показывает, что есть ошибки типа: cin, cout, system не являются однозначными, всего 17 ошибок, подчеркивает красным эти операторы, как это убрать?

#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
int** P1, ** P2, ** P3, n, m;
cout << "Введите кол-во строк матрицы: ";
cin >> n;
cout << "Введите кол-во столбцов матрицы: ";
cin >> m;
P1 = new int* [n];
for (int i = 0; i < n; i++)
    P1[i] = new int[m];
srand(time(0));
for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)  //рандом 1 матрицы
        P1[i][j] = rand() % 10;
for (int i = 0; i < n; i++)
{
    cout << endl;                  //вывод 1 матрицы
    for (int j = 0; j < m; j++)
    {
        cout << setw(3) << P1[i][j] << "t";
    }
}
cout << endl;
int k;
cout << "Введите кол-во столбцов 2 матрицы: ";
cin >> k;
P2 = new int* [k];
for (int i = 0; i < m; i++)
    P2[i] = new int[k];
for (int i = 0; i < m; i++)
    for (int j = 0; j < k; j++)  //рандом 2 матрицы
        P2[i][j] = rand() % 10;
for (int i = 0; i < m; i++)
{
    cout << endl;                  //вывод 2 матрицы
    for (int j = 0; j < k; j++)
    {
        cout << setw(3) << P2[i][j] << "t";
    }
}
cout << endl;
P3 = new int* [n];
for (int i = 0; i < n; i++)
    P3[i] = new int[k];
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < k; j++)  //умножение матриц
    {
        P3[i][j] = 0;
        for (int z = 0; z < m; z++)
            P3[i][j] = P3[i][j] + P1[i][z] * P2[z][j];
    }
}
cout << endl << "Результат умножения:" << endl;
for (int i = 0; i < n; i++)                     //вывод результата 
 умножения
{
    cout << endl;
    for (int j = 0; j < k; j++)
        cout << setw(3) << P3[i][j] << "t";
}
cout << endl;
for (int i = 0; i < n; i++)
    delete[] P1[i];
delete[] P1;
for (int i = 0; i < m; i++)
    delete[] P2[i];
delete[] P2;
for (int i = 0; i < n; i++)
    delete[] P3 [i];
delete[] P3;
system("pause");
return 0;
}

1 / 1 / 4

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

Сообщений: 247

1

15.06.2017, 20:47. Показов 68977. Ответов 1


Добрый день, при написании кода я столкнулся с проблемой, cout везде выбивает «
«cout» не является однозначным С++», как решить эту проблему?

Условие : «С помощью перегруженных функций реализуем задачу для различных типов массивов, например для типов int и float. «
Код:

C++
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <iostream>
 
using namespace std;
//-------------------------------------
void Init_mas(int m, float *x)// перегруженная функция
{
  cout<<"Введите массив:n";
  for(int i=0;i<n;i++) {
   cout<<"a[“<<i<<”] = "; cin>>x[i];
  }
}
//-------------------------------------
void Init_mas(int m, int *x)
{
  cout<<"Введите массив:n";
  for(int i=0;i<n;i++) {
   cout<<"a[“<<i<<”] = "; cin>>x[i];
  }
}
//-------------------------------------
int Nomer_el(int m, float *x) // перегруженная функция
{
 int k=0; //номер минимального элемента
 float min= x[0];
 for(i=0;i<m;i++){
   if(x[i]<min){ k=i; min=x[i]}
 }
 return k;
}
//------------------------------------
int Nomer_el(int m, int *x){
 int k=0; //номер минимального элемента
 float min= x[0];
 for(i=0;i<m;i++){
   if(x[i]<min){ k=i; min=x[i]}
 }
 return k;
}
//------------------------------------
float Summa_el(int m, float *x)// перегруженная функция
{
 float s=0; //сумма
 for(i=0;i<m;i++) {
    if((i%2)==0)s+=a[i];
 }
 return s;
}
//--------------------------------------
int Summa_el(int m, int *x)
{
 float s=0; //сумма
 for(i=0;i<m;i++)
 {
    if((i%2)==0)s+=a[i];
 }
 return s;
}
//----------------------------------------
int main() {
   cout <<"Для массива вещественного типа "<<endl;
  float *a;
  int n; 
  cout<<"Введите длину массива: "; cin>>n;
  a=new float[n]; //создание динамического массива
  Init_mas(n,a);
int m=0; //номер минимального элемента
  float s=0; //сумма
  m = Nomer_el(n,a);  s = Summa_el(n,a);
  for(i=0;i<n;i++){
   if(a[i]<0.0){
    for(int j=i;j<n-1;j++)a[j]=a[j+1];
    a[j] = 0;
}
   }
   cout<<"1)номер минимального элемента массива: ";
  cout<<m<<endl;
  cout<<"2)сумма элементов с четными номерами: "
  cout<<s<<endl;
  cout<<"nСжатие массива и вывод на экран.n";
  for(i=0;i<n;i++) printf("a[%d] = %5.2fn",i,a[i]);
  delete(a); //уничтожение массива
}
// тоже самое для массива целого типа
 {
  cout <<"Теперь для массива целого типа "<<endl;
  int *a, n; clrscr();
  cout<<"Введите длину массива: "; cin>>n;
  a=new int[n]; //создание динамического массива
  Init_mas(n,a);
  int m=0; //номер минимального элемента
  float s=0; //сумма
  m = Nomer_el(n,a); s = Summa_el(n,a);
0){
    for(int j=i;j<n-1;j++)a[j]=a[j+1];
    a[j] = 0;
  }
 }
  cout<<"1)номер минимального элемента массива :"
 cout<<m<<endl;
  cout<<"2) сумма элементов с четными номерами : "
cout<<s<<endl;
  cout<<"nСжатие массива и вывод на экран.n";
   for(i=0;i<n;i++) printf("a[%d] = %5.2fn",i,a[i]);
  delete(a); //уничтожение массива
 }
 getch();
 return 0;
}

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

0

  • Forum
  • General C++ Programming
  • Cout is ambiguous?

Cout is ambiguous?

What does that mean? How do I fix it?

Post the actual error message, as well as the line of code which is causing the error.

Post your code so that it is [code]between code tags[/code] as this will give it syntax highlighting and line numbers.

Please copy and paste the exact error message, and indicate which line the error is talking about.

Last edited on

Well, I am working on this bank database project and whenever I post this part:

void addaccount()
{
ifstream inData;
ofstream outData;
string fileName;
string str;
cout << «Insert the name of the data file: «;
cin >> fileName;
inData.open(fileName); // Access the file of the name you had inputted
string lastName, firstName, type;
double balance;
inData >> lastName >> firstName >> balance >> type;
cout << «What file would you like to save the data in?: «;
cin >> fileName;
outData.open(fileName);
outData << str;
cout << «nEnter the customer’s last name:»;
cin >> lastName;
cout << «nnEnter the customer’s first name : «;
cin >> firstName;
cin.ignore();
cin.getline(50, firstName);
cout << «nEnter Type of The account (C/S) : «;
cin >> type;
type = toupper(type);
cout << «nEnter The Initial amount(>=500 for Saving and >=1000 for current ) : «;
cin >> deposit;
cout << «nnnAccount Created.»;
}

void deleteaccount();
{
account ac;
ifstream inFile;
ofstream outFile;
inFile.open(«account.dat», ios::binary);
if (!inFile)
{
cout << «File could not be open !! Press any Key…»;
return;
}
outFile.open(«Temp.dat», ios::binary);
inFile.seekg(0, ios::beg);
while (inFile.read(reinterpret_cast<char *> (&ac), sizeof(account)))
{
if (ac.retacno() != n)
{
outFile.write(reinterpret_cast<char *> (&ac), sizeof(account));
}
}
inFile.close();
outFile.close();
remove(«account.txt»);
rename(«Temp.txt», «account.txt»);
cout << «nntRecord Deleted ..»;
}

void search();
{
int seqSearch(const int list[], int listLength, int searchItem)
{
int loc;
bool found = false;

for (loc = 0; loc < listLength; loc++)
if (list[loc] == searchItem)
{
found = true;
break;
}
if (found)
return loc;
else
return -1;
}

into it, all the couts get the error message IntelliSense: «cout» is ambiguous.

Speaking of which, I really need help with that. I have a topic called ‘Bank Database’ I could really use help with.

IntelliSense errors aren’t compilation errors. Sometimes IntelliSense can get confused or out of date.

Go to Build -> Rebuild

You may also consider trying to prefix your ‘cout’ object with its namespace, ‘std’. In other words, wherever you’ve put

cout << "Information";

You may consider putting

std::cout << "Information";

Perhaps there are multiple objects called ‘cout’ in your program (or you’ve included external libraries which also have a cout object) and providing a namespace might give some clarification as to which one you mean.

Topic archived. No new replies allowed.

vsliv368:30146709
vsreu685:30147344
python383:30185418
vspor879:30202332
vspor708:30202333
vspor363:30204092
vslsvsres303:30308271
vserr242:30382549
pythontb:30283811
vsjup518:30340749
pythonptprofiler:30281270
vshan820:30294714
vstes263:30335439
vscod805cf:30301675
binariesv615:30325510
bridge0708:30335490
bridge0723:30353136
cmake_vspar411:30581797
vsaa593:30376534
pythonvs932:30410667
cppdebug:30492333
vsclangdf:30486550
c4g48928:30535728
dsvsc012cf:30540253
pynewext54:30695312
azure-dev_surveyone:30548225
2e4cg342:30602488
pyind779:30671433
89544117:30613380
pythonsymbol12:30671437
showlangstatbar:30737416
vsctsb:30748421
pythonms35:30701012
pythonfmttext:30731395
fixhidewlkth:30730051
showsbindicator:30730056
pythongtdpathcf:30739705

Ok I am trying to port my vending machine program from Java to C++, this isn’t going a smoothly as I had planned however. And I get the following errors whenever I try to use cout.

C2872: ‘cout’ : ambiguous symbol
 C2679: binary ‘<<‘ : no operator defined which takes a right-hand operand of type ‘class std::basic_string<char,struct std::char_traits<char>,class std::allocator
<char> >’ (or there is no acceptable conversion)

I have to files a header file called classes.h and main file called vmachine.cpp. I am using MSVC++ 6. Here is the code respectively.


/*This file contains all the classes necessary to
 *operate the main vending machine program
 */

#include <iostream>
#include <string>
using namespace std;

class Bank {
public:
    Bank();
    ~Bank() {}
    int addCred(int addCred) {
        currCred += addCred;
        totalCred += addCred;
        return currCred;
    }
    int giveChange(int deductCred){
        currCred -= deductCred;
        totalCred -= deductCred;
        return currCred;
    }
    void updateCred(int cred) { currCred = cred; }
    int getCred() { return currCred; }
private:
    int currCred;
    int totalCred;
};

Bank::Bank() {
    currCred = 0;
    totalCred = 2000;
}

class Display {
public:
    Display();
    ~Display() {}
    void showDisplay(string displayText) {        
        text = displayText;        
        cout<<«DISPLAY:: » <<text;
    }
    void clear() {
       text = «READY»;       
       showDisplay(text);
    }
private:
    string text;
};

Display::Display() {}

class Keypad {
public:
    Keypad();
    ~Keypad() {}
    string getCode() {
//        cin.getline((char*)code.data(), 10, ‘n’);        
        strupr((char*)code.data());
        return code;
    }
private:
    string code;
};

Keypad::Keypad() {}

class Product{
    public:
        // default constructor (an added benefit is that it can
        // be initalized with a string literal)
        Product(const char* itsName = «», int itsPrice = 0):
          name(itsName), price(0)
          {}
        // normal constructor
        Product(const string& itsName, int itsPrice):
        name(itsName), price(itsPrice)            {}
        // if your destructor doesn’t need to do anything,
        // you don’t need to implement one
        // since these functions don’t modify the object (and shouldn’t), mark them as const
        const string& getName() const {return name;}
        int getPrice() const {return price;}
    private:
        string name;
        int price;
};

class Tray{
    public:
        Tray(const char* itsCode = «»):
          code(itsCode), prod()
          {}
        Tray(const string& itsCode, const Product& trayItem):
          limit(20), quantity(20), code(itsCode), prod(trayItem)
          {}
          // I’m guessing that you don’t need a deconstructor here, either
          const string& getCode() const {return code;}
          const Product& getProduct() const {return prod;}
          int getQuant() const {return quantity;}
          void dispense() {—quantity;}
    private:
        int limit;
        int quantity;
        string code;
        Product prod;
};


#include <iostream.h>
#include <string>
#include «classes.h»
using namespace std;

Tray *tray_prod_init() {

    Tray *t_array = new Tray[20];

    //Set up List of Products

    Product mars(«Mars»,40);
    Product Snickers(«Snickers»,40);
    Product Wispa(«Wispa»,35);   

    //Set up List of trays
    Tray A1(«A1»,mars);
    Tray A2(«A2»,Snickers);
    Tray A3(«A3»,Wispa);   

    //Assign position in array for each tray

    t_array[0] =  A1;
    t_array[1] =  A2;
    t_array[2] =  A3;    

    return t_array;

}

void interface1(Tray tList[],Bank* moneyBag,Display* display,Keypad* keypad) {    

}

void interface2(Tray tList[],Bank* moneyBag,Display* display,Keypad* keypad) {

}

void interface3(Tray tList[],Bank* moneyBag,Display* display,Keypad* keypad) {

}

void main() {

    //Create objects needed
    Tray* tList = tray_prod_init();    // use tList
    Bank* moneyBag = new Bank();
    Display* display = new Display();
    Keypad* keypad = new Keypad();

    //Run the interface menu
    interface1(tList,moneyBag,display,keypad);

    //Delete objects
    delete[] tList; // MAKE SURE YOU DO THIS WHEN YOU’RE DONE!!!
    delete moneyBag;
    delete display;
    delete keypad;

}

  1. Whenever you see a compiler error that says something is ambiguous it normally means that you have opened some namespaces (ie using namespace std;)
  2. Try changing your code to use std::cout and see what the compiler says.

What does ambiguous mean in C++?

Access to a base class member is ambiguous if you use a name or qualified name that does not refer to a unique function or object. The declaration of a member with an ambiguous name in a derived class is not an error.

What is cout << in C?

The “c” in cout refers to “character” and ‘out’ means “output”, hence cout means “character output”. The cout object is used along with the insertion operator << in order to display a stream of characters. The general syntax is: cout << varName; Or.

What does cout does not name a type mean?

Loading when this answer was accepted… The problem is that the code you have that does the printing is outside of any function. Statements in C++ need to be inside a function.

What is does not name a type error?

7 Answers. When the compiler compiles the class User and gets to the MyMessageBox line, MyMessageBox has not yet been defined. The compiler has no idea MyMessageBox exists, so cannot understand the meaning of your class member. You need to make sure MyMessageBox is defined before you use it as a member

How do you declare cout in scope?

2 Answers. Put the following code before int main() : using namespace std; And you will be able to use cout

How do I fix error cout was not declared in this scope?

specify the namespace you’ re using. 1 #include 2 using namespace std; 3 4 int main () 5 { 6 cout << “Hello World!n” << endl; 7 return 0; 8 } Adding “using namespace std;” to the top of the file tells c++ what namespace you’

How do you use cout?

Standard input stream (cin)

  1. #include
  2. using namespace std;
  3. int main( ) {
  4. int age;
  5. cout << “Enter your age: “;
  6. cin >> age;
  7. cout << “Your age is: ” << age << endl;
  8. }

What is not declared in this scope Arduino?

If you try to do something like this: void loop() { digitalWrite(pin, LOW); // wrong: pin is not in scope here. } you’ll get the same message as before: “error: ‘pin’ was not declared in this scope”. That is, even though you’ve declared pin somewhere in your program, you’re trying to use it somewhere outside its scope

What is not declared in this scope C error?

you declare and initialize the variables y, c , but you don’t used them at all before they run out of scope. That’s why you get the unused message. Later in the function, y, c are undeclared, because the declarations you made only hold inside the block they were made in (the block between the braces {…} )

What language is Arduino?

a c/c++

How do you declare a scope?

When you declare a variable using the var keyword, the scope is as follows:

  1. If the variable is declared outside of any functions, the variable is available in the global scope.
  2. If the variable is declared within a function, the variable is available from its point of declaration until the end of the function definition.

Which type of variable Cannot be declared within a procedure in VBA?

All static variables are declared within a procedure and can’t declare outside procedure. Static variable always retains its value even after the procedure ends until the project terminates. This static variable is not available for other procedures.

What is difference between local and global variable?

Local variable is declared inside a function whereas Global variable is declared outside the function. Local variables are created when the function has started execution and is lost when the function terminates, on the other hand, Global variable is created as execution starts and is lost when the program ends.6 天前

What is the purpose of namespace?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries

What is namespace example?

A namespace is a group of related elements that each have a unique name or identifier. A file path, which uses syntax defined by the operating system, is considered a namespace. For example, C:Program FilesInternet Explorer is the namespace that describes where Internet Explorer files on a Windows computer

What is the difference between namespace and class?

Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention

What is the default namespace A program will run in?

A namespace is basically a system to make sure that all the names in a program are unique and can be used without any conflict. You might already know that everything in Python—like strings, lists, functions, etc. —is an object. Another interesting fact is that Python implements namespaces as dictionaries

How do namespaces work?

A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it. Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope

What is the scope resolving rule of Python?

The LEGB rule is a kind of name lookup procedure, which determines the order in which Python looks up names. For example, if you reference a given name, then Python will look that name up sequentially in the local, enclosing, global, and built-in scope.

What is dir () in Python?

Python dir() Function The dir() function returns all properties and methods of the specified object, without the values. This function will return all the properties and methods, even built-in properties which are default for all object.

How do you use help in Python shell?

The python help function is used to display the documentation of modules, functions, classes, keywords etc. If the help function is passed without an argument, then the interactive help utility starts up on the console

What does DIR mean?

DIR

Acronym Definition
DIR Directory
DIR Director
DIR Direction
DIR Department of Industrial Relations

What is eval () function in Python?

Python’s eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you’re trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object

Why is eval bad python?

Using eval is weak, not a clearly bad practice. It violates the “Fundamental Principle of Software”. Your source is not the sum total of what’s executable. In addition to your source, there are the arguments to eval , which must be clearly understood

How do you evaluate?

To evaluate an expression, we substitute the given number for the variable in the expression and then simplify the expression using the order of operations. To evaluate, substitute 3 for x in the expression, and then simplify.

Is eval safe python?

Python eval() function is very powerful. Even though we have globals and locals variable to restrict access, they are not enough and workaround are available to harm your system. Read this article explaining why eval is dangerous. You shouldn’t use eval() function with untrusted user inputs.

Why eval is dangerous?

eval() is a dangerous function, which executes the code it’s passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user’s machine with the permissions of your webpage / extension

What does type () do in Python?

The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.

Is nonlocal a keyword in Python?

nonlocal is a keyword (case-sensitive) in python, it is used when we work with the nested functions and we need to use a function which is declared in outer function, if we do the same, a variable will be created as local and we then we will not be able to work with a variable in inner function which is declared in ..

Понравилась статья? Поделить с друзьями:
  • Counter strike global offensive ошибка при загрузке
  • Counter strike global offensive ошибка engine error
  • Control ошибка dx11
  • Control ошибка device removed
  • Control socket has closed unexpectedly iperf3 ошибка