Error c2088 illegal for class

Ошибка при компиляции "error C2088: <<: недопустимо для class" C++ Решение и ответ на вопрос 1785743

0 / 0 / 0

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

Сообщений: 23

1

26.07.2016, 13:00. Показов 8923. Ответов 12


Доброго времени суток
у меня при компиляции возникает ошибка
1>main.cpp(493): error C2088: <<: недопустимо для class
суть в том что я все пересмотрел все норм прописано
насколько я понимаю оно говорит типа ошибка в скобках на cout но я не нашел эту ошибку
эта ошибка не отмечается visual studio только при запуску локального отладчика она вылазит
1 мне нужно узнать знает кто то что с этим делать
2 если я не ошибаюсь в visual studio можно запустить выполнение задачи до определенной точки с просмотром действий
если можно дайте ссылку на статью или на видео
за ранние благодарю!!!!!!

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



0



257 / 234 / 185

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

Сообщений: 898

26.07.2016, 13:05

2

Кидай сюда код.
Пошаговая отладка f10.



1



Модератор

Эксперт С++

12641 / 10135 / 6102

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

Сообщений: 27,170

26.07.2016, 13:09

3



1



INSIDERS

0 / 0 / 0

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

Сообщений: 23

26.07.2016, 13:51

 [ТС]

4

код очень большой
суть в том что там очень много этих скобок в этом коде генерируется html страницы(мне уже надоело его делать уже 3 вопрос по тому самому коду) и я добавил туда всего навсего if else типа в зависимости от выбора пользователя присваивается
определенные строки
то что я добавил

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
cout << "Rакой вид стенда вы используете проект 2? " << endl;
        cout << "NEO di mare = 1" << endl;
        cout << "NEO = 2" << endl;
        cout << "NEO NICK = 3" << endl;
        cout << "NEO ELF = 4" << endl;
        cin >> standconfiguration2;
 
        if (standconfiguration2 != 0 || standconfiguration2 < 4)
        {
            if (standconfiguration2 == 1)
            {
                standselection2 = "гнутых стекол системы Di Mare";
                stand2 = "NEO Di Mare";
            }
            if (standconfiguration2 == 2)
            {
                standselection2 = "прямых стекол системы NEO";
                stand2 = "NEO ";
            }
            if (standconfiguration2 == 3)
            {
                standselection2 = "гнутых и прямых стекол система Nick";
                stand2 = "NEO Nick";
            }
            if (standconfiguration2 == 4)
            {
                standselection2 = "гнутых и прямых стекол система Elf";
                stand2 = "NEO Elf";
            }
        }
        else cout << "Выберите стенд в диапазоне от 1 до 4!!!";



0



Объявлятель переменных

1199 / 389 / 315

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

Сообщений: 1,232

26.07.2016, 14:03

5

Пробовали тот же код с использованием switch сделать? И где ошибка-то выскакивает?



1



0 / 0 / 0

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

Сообщений: 23

26.07.2016, 14:11

 [ТС]

6

ну со switch я не пробовал
ошибка появляется во время компиляции
1>main.cpp(493): error C2088: <<: недопустимо для class
и не хочет запускать



0



257 / 234 / 185

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

Сообщений: 898

26.07.2016, 14:15

7

Значит вы не перезагрузили operator<< и пытаетесь его использовать наверное…



1



0 / 0 / 0

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

Сообщений: 23

26.07.2016, 14:33

 [ТС]

8

то есть если я скопирую весь код пересоздам проект это поможет ?



0



257 / 234 / 185

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

Сообщений: 898

26.07.2016, 14:39

9

INSIDERS, Тогда бы так делали все программисты..



1



Объявлятель переменных

1199 / 389 / 315

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

Сообщений: 1,232

26.07.2016, 14:48

10

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

ошибка появляется во время компиляции
1>main.cpp(493): error C2088: <<: недопустимо для class

Я честно пытался найти в приведённом выше коде 493 строку, но не преуспел.



1



0 / 0 / 0

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

Сообщений: 23

26.07.2016, 15:14

 [ТС]

11

я не программист пока что не те знания
Да к что ты можешь мне посоветовать по этому поводу?

Добавлено через 2 минуты
aахахахаахахахах
как включить нумерацию в visual studio?

Добавлено через 20 минут
<< «<h3 style=»text — align: left; «Добрый день,» << name << «.</h3>» << «n»
вот эта строка )))



0



16495 / 8988 / 2205

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

Сообщений: 15,611

26.07.2016, 16:17

12

INSIDERS, кавычки внутри строки надо экранировать.



1



SpBerkut

Объявлятель переменных

1199 / 389 / 315

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

Сообщений: 1,232

26.07.2016, 16:26

13

Если синтаксис подсветить, то всё становится очевидным.

C++
1
<<"<h3 style="text - align: left; "Добрый день," << name << ".</h3>" << "n"



1



Я изучаю шаблоны C ++, и у меня есть функция для различных типов карт:

template<typename T> void foo(T m1, T m2){ //map m1 and map m2
map<pair<T, int>, int>::iterator itr1 = m1.begin();
map<pair<T, int>, int>::iterator itr2 = m2.begin();

while (itr1 != m1.end() && itr2 != m2.end()){
//do something with itr1 and itr2
}
}

Когда я компилирую его в VS2013, я получил ошибку: error C2088: '!=' : illegal for class что указывает на while (itr1 != m1.end() && itr2 != m2.end()), Но если я явно объявляю тип карт (то есть не использую шаблон), у меня нет ошибки. Кто-нибудь может сказать мне, что я здесь делаю не так? Спасибо!

-3

Решение

std::map<pair<T, int>, int>::iterator является итератором с карты, тип ключа которого pair<T, int> (где T по-видимому, также map в вашем примере) и какой тип значения int, который явно отличается от typename T::iterator который является типом m1.begin(), Что вы, вероятно, хотите, это:

template<typename T>
void foo(T m1, T m2) {
typename T::iterator itr1 = m1.begin();
/* ... */
}

Или же:

template <typename T>
void foo(std::map<std::pair<T, int>, int> m1,
std::map<std::pair<T, int>, int> m2) {
typename T::iterator itr1 = m1.begin();
/* ... */
}

В первом случае параметр шаблона является типом map (T = std::map<std::pair<T, int>>) в то время как во втором случае это тип первого атрибута ключа карты.

2

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

Других решений пока нет …

I’m getting a C2088 error on the first attempt to compile a clean MEPlaybackNative solution.  I just downloaded the solution from MSDN, unzipped it, opened it with VS12-RP, and built the project.  I get the error below at the location marked in
the code below.

Is there some update or build/compiler setting that I’m missing?

C:Program Files (x86)Microsoft Visual Studio 11.0VCincludeagile.h(188): error C2088: ‘!=’ : illegal for class
(VideoView.cpp)

		Agile<T> operator=(const Agile<T>& object) throw()
		{
			if(_object != object)<--line 188, calls "!=" illegal?
			{
				// Get returns pointer valid for current context
				SetObject(object.Get());
			}
			return _object;
		}

1> C:Program Files (x86)Microsoft Visual Studio 11.0VCincludeagile.h(187) : while compiling class template member function ‘Platform::Agile<T> Platform::Agile<T>::operator =(const Platform::Agile<T> &) throw()’

1> with

1> [

1> T=Windows::UI::Core::CoreWindow

1> ]

1> e:multimediaprojectsmedia engine native c++ video playback samplec++MEPlayer.h(160) : see reference to class template instantiation ‘Platform::Agile<T>’ being compiled

1> with

1> [

1> T=Windows::UI::Core::CoreWindow

1> ]

Here is my code where I try to access an element of class Edge:

#include <iostream> 
// for the sort()
#include <algorithm>
#define PI 3.14159265358979323846

struct Point{
    Point(int xx, int yy): x(xx), y(yy) { }
int x;
int y;
};

// class Edge: representing lines segments of the poly-line
struct Edge{
    // constructor
    Edge(Point p0, Point p1) : start(p0), end(p1){ 
        if (p0.x == p1.x && p0.y == p1.y) throw std::invalid_argument("Edge: Identical points!"); 
    } 
    // operator< defined for the sorting by increasing ordinate of the end point
    bool operator<(const Edge& e){ return (end.y < e.end.y); }
    // data members: start point and end point of the line
Point start;
Point end;
};

static void generatePoints(vector<Point>& p){
p.push_back(Point(50,50));
p.push_back(Point(200,50));
p.push_back(Point(200,200));
p.push_back(Point(50,200));
}
//------------------------------------------------------------------------------------------------
int main(){

// Generate points for the poly-line
vector<Point> polyPoints;
generatePoints(polyPoints);

vector<Edge> polyEdges;
Point first = polyPoints(0);
Point last = polyPoints(polyPoints.size()-1);
polyEdges.push_back(Edge(last, first));
for (size_t i = 1; i < polyPoints.size(); ++i) polyEdges.push_back(Edge(polyPoints[i-1], polyPoints[i]));


int yCoordinate = polyEdges[i].end.y;

return 0;
}

Now, I have a vector of edges, like so:

vector<Edge> polyEdges;

and when I try to access it a specific member polyEdges[i].end.y, I get the following error message:

  'vector' : undeclared identifier
  'Point' : illegal use of this type as an expression
  see declaration of 'Point'
  'p' : undeclared identifier
  'generatePoints' : function-style initializer appears to be a function definition
  vector' : undeclared identifier
  see declaration of 'Point'
  'polyPoints' : undeclared identifier
  'Point' : illegal use of this type as an expression
  'polyPoints' : undeclared identifier
  'generatePoints': identifier not found
  'vector' : undeclared identifier
  Edge' : illegal use of this type as an expression
  see declaration of 'Edge'
  error C2088: '[' : illegal for class
  polyEdges' : undeclared identifier
  'polyPoints': identifier not found
  'polyPoints' : undeclared identifier
  left of '.size' must have class/struct/union
  'Point' : illegal use of this type as an expression
  error C2228: left of '.end' must have class/struct/union
  error C2228: left of '.y' must have class/struct/union

It must be related with the overloading of the []operator.

Question:

Should I overload [] operator and if so, how to do it?

Here is my code where I try to access an element of class Edge:

#include <iostream> 
// for the sort()
#include <algorithm>
#define PI 3.14159265358979323846

struct Point{
    Point(int xx, int yy): x(xx), y(yy) { }
int x;
int y;
};

// class Edge: representing lines segments of the poly-line
struct Edge{
    // constructor
    Edge(Point p0, Point p1) : start(p0), end(p1){ 
        if (p0.x == p1.x && p0.y == p1.y) throw std::invalid_argument("Edge: Identical points!"); 
    } 
    // operator< defined for the sorting by increasing ordinate of the end point
    bool operator<(const Edge& e){ return (end.y < e.end.y); }
    // data members: start point and end point of the line
Point start;
Point end;
};

static void generatePoints(vector<Point>& p){
p.push_back(Point(50,50));
p.push_back(Point(200,50));
p.push_back(Point(200,200));
p.push_back(Point(50,200));
}
//------------------------------------------------------------------------------------------------
int main(){

// Generate points for the poly-line
vector<Point> polyPoints;
generatePoints(polyPoints);

vector<Edge> polyEdges;
Point first = polyPoints(0);
Point last = polyPoints(polyPoints.size()-1);
polyEdges.push_back(Edge(last, first));
for (size_t i = 1; i < polyPoints.size(); ++i) polyEdges.push_back(Edge(polyPoints[i-1], polyPoints[i]));


int yCoordinate = polyEdges[i].end.y;

return 0;
}

Now, I have a vector of edges, like so:

vector<Edge> polyEdges;

and when I try to access it a specific member polyEdges[i].end.y, I get the following error message:

  'vector' : undeclared identifier
  'Point' : illegal use of this type as an expression
  see declaration of 'Point'
  'p' : undeclared identifier
  'generatePoints' : function-style initializer appears to be a function definition
  vector' : undeclared identifier
  see declaration of 'Point'
  'polyPoints' : undeclared identifier
  'Point' : illegal use of this type as an expression
  'polyPoints' : undeclared identifier
  'generatePoints': identifier not found
  'vector' : undeclared identifier
  Edge' : illegal use of this type as an expression
  see declaration of 'Edge'
  error C2088: '[' : illegal for class
  polyEdges' : undeclared identifier
  'polyPoints': identifier not found
  'polyPoints' : undeclared identifier
  left of '.size' must have class/struct/union
  'Point' : illegal use of this type as an expression
  error C2228: left of '.end' must have class/struct/union
  error C2228: left of '.y' must have class/struct/union

It must be related with the overloading of the []operator.

Question:

Should I overload [] operator and if so, how to do it?

Итак, я только начинаю нелегкий путь в C++, так что решил сделать несложную программу: выдача вопросов и счет баллов за них. В суть углубляться не буду, но идея работы программы такая: в подключаемом файле я создаю и инициализирую двумерный вектор, каждый элемент которого строка с вопросом, так же я храню кол-во тем. Сейчас для примера будет 1 тема, но это не важно. Важно то, что при попытке сделать это получаю каскад ошибок, и вопрос: что я делаю не так и как это сделать лучше?
Код:

#ifndef QPACK1_H
#define QPACK1_H

int theme_amount = 1;
std::vector<std::vector<std::string> > questions(theme_amount + 1, std::vector<std::string>(6, " "));


questions[1][0] = "Вы попали на тему: Name of the themen" ;    // сначала номер темы, потом номер вопроса(по 5), 0 вопрос - название темы.

questions[1][1] = "Question 1";
questions[1][2] = "Question 2";
questions[1][3] = "Question 3";
questions[1][4] = "Question 4";
questions[1][5] = "Question 5";


#endif

Список ошибок:

1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(8,1): error C2466: невозможно выделить память для массива постоянного нулевого размера
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(8,17): error C2087: questions: отсутствует индекс
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(8,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(10,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(10,1): error C2040: questions: "int [1][1]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(11,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(11,1): error C2040: questions: "int [1][2]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(12,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(12,1): error C2040: questions: "int [1][3]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(13,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(13,1): error C2040: questions: "int [1][4]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(14,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(14,1): error C2040: questions: "int [1][5]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2CHGK_game.cpp(44,52): error C2088: [: недопустимо для class
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2CHGK_game.cpp(46,48): error C2088: [: недопустимо для class

Основной код программы:

#include <vector>
#include <iostream>
#include <string>

#include "qpack1.h" //список вопросов



struct players
{
    std::vector<std::string> name;
    std::vector<int> score;
};




int main()
{   
    int pl_amount, qst_number = 0;
    players plist;
    std::string input;
    
    std::cout << "Enter number of players(less then 10): ";
    std::cin >> pl_amount;
    
    plist.name.resize(pl_amount);
    plist.score.resize(pl_amount);
    plist.score.assign(plist.score.size(), 0);

    std::cout << "Enter players names: n";
    for (int i = 0; i < pl_amount; i++)
        std::cin >> plist.name[i];

    std::cout << "Tips: enter stop to left the game. nUse + or - and number of player to give(take out) points to his score.n";
    for (int theme_number = 1; theme_number <= theme_amount; theme_number++)
    {

        while (qst_number <= 4)
        {
            qst_number++;
            if (qst_number == 1)
                std::cout << questions[theme_number][0] << "n";

            std::cout << questions[theme_number][qst_number] << "n";

            TryAgain:
            getline(std::cin, input);

            if (input == "stop")
                goto Results;

            if(input.size() != 2 || !(input[1] > '0' && input[1] <= '9'))
            {
                std::cout << "Incorrect input.n";
                goto TryAgain;
            }

            if(input[1] - '0' > pl_amount || input[1] - '0' <= 0)
            {
                std::cout << "Incorrect input(Player was not found).n";
                goto TryAgain;
            }

            if (input[0] == '+')
            {
                plist.score[input[1] - '0' - 1] += qst_number * 10;
                std::cout << plist.name[input[1] - '0' - 1] << " Gets + " << qst_number * 10 << " points!n";
            }
            else
                if (input[0] == '-')
                {
                    plist.score[input[1] - '0' - 1] -= qst_number * 10;
                    std::cout << plist.name[input[1] - '0' - 1] << " Gets - " << qst_number * 10 << " points!n";
                }
                else { std::cout << "Please start input with + or -.n";goto TryAgain; }
                     


        }
        qst_number = 0;
    }

    Results:
    std::cout << "The final score is: n";

    for (int j = 0; j < pl_amount; j++)
        std::cout << plist.name[j] << " : " << plist.score[j] << " points. n";
}

И еще есть проблема: при первом выводе темы и вопроса, сразу же после этого выводится Incorrect input, хотя ничего не было введено. (проверял заккоментив эту часть: )

questions[1][0] = «Вы попали на тему: Name of the themen» ; //
сначала номер темы, потом номер вопроса(по 5), 0 вопрос — название
темы.

questions[1][1] = "Question 1";
questions[1][2] = "Question 2";
questions[1][3] = "Question 3";
questions[1][4] = "Question 4";
questions[1][5] = "Question 5";

В общем, как фиксить?)

Help, I’m getting the following error message:

error C2040: ‘money’ : ‘double’ differs in levels of indirection from ‘char [15]’
error C2088: ‘>>’ : illegal for class

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
#include <string.h>
using namespace std;

string FileName;
void starline();
float balance;
float deposit;
float check;
double m; 

void starline() //function declarator
{
for(int j=0; j<65; j++) //function body
cout << '-';
cout << endl;
}


int main()
{
    cout << "Enter a file name (including extension): " << endl;
    char FileName[300];
    cin.getline (FileName,300);
    ifstream input(FileName);

    if (!input.good())
    {
        cerr << "Unable to open file" << endl;
        exit(1);
    }

    while (!input.eof())
    {
        starline();
        char    deposit[15];
        input.getline(deposit, 15, ':');
        cout << left << setw(15) << deposit;

        char    date[15];
        input.getline(date, 15, ':');
        cout << setw(15) << date;

        char    place[15];
        input.getline(place, 15, ':');
        cout << setw(15) << place;

        char money[15];
        input.getline(money,15);
        cout << right  << setw(15) << "$ " << money << right << endl;
        starline();

        ifstream fin;
        double money = 0.0;
        fin.open(FileName);

        double m = atof ( money);
        //test for success, of course
        fin >> money; //input stored in the double

    }




    return 0;
}
  • Forum
  • Beginners
  • HELP! CANNOT UNDERSTAND ERROR MESSAGE!!

HELP! CANNOT UNDERSTAND ERROR MESSAGE!!

Here is the current code i am trying to run. i see nothing wrong with it but the errors are listed below

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
#include<iostream>
#include<string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

//Declerations
//Question Strings
string a; //Asking if you want to play
string b; //Asking if you want to draw red or blue
string c; //Asking if you want to go back to the menu
string d; //Asking if you want to play again
//Variable Declerations
int r; //Variable With A Random Value
int t; //Variable With Your Total Score
int d; //Pick a deck
int red; //Prepping Red Matrix
int blue; //Prepping Blue Matrix

//Microprogram Declerations
int MAIN();
int PLAY();
void RULES();
void DETERMINE();
void SETVALUES();
void LOSS();

//---------------------------------------------------------------

//Active Play
int PLAY(){
system("cls");
srand ( time(NULL) );
r = rand() % 1 + 0;
cout<<"Your total is "<< t <<"!"<<endl;
cout<<"Pick a deck"<<endl;
cout<<"Red or Blue"<<endl;
cin>> d;
if (d == "Red" || d == "red"){
t = t + red[r];
DETERMINE();
}
if (d == "Blue" || d == "blue"){
t = t + blue[r];
DETERMINE();
}
else
PLAY();
}

//If the player has lost, do this
void loss(){
system("cls");
cout<<"You Have Lost"<<endl;
system("pause");
return;
}

//Algorithim to determine weather or not the player has been stupid enough to lose a game of luck yet.
void DETERMINE(){
if (t > 0)
PLAY();
if (t == 0 || t < 0)
LOSS();
else{
system("cls");
cout<<"FATAL SYSTEM ERROR"<<endl;
system("pause");
return;
}

//Setting the initials Values
void SETVALUES(){
t = 500;
int red[0] = {-50};
int red[1] = {50};
int blue[0] = {-100};
int blue[1] = {100};
}

//Telling the player the rules
void RULES(){
cout<<"The Rules of the game are simple"<<endl;
cout<<"You start out with 500 dollars"<<endl;
cout<<"Draw from either the Red or the Blue deck"<<endl;
cout<<"Each deck has card that either add or subtract from your pool"<<endl;
cout<<"Have Fun!";
cout<<"press anykey to go back to the menu"<<endl;
system("pause");
MAIN();
return;

//Starting Welcome Menu
int MAIN(){
system("cls");
cout<<"Welcome to the Red Blue Card Game"<<endl;
cout<<"Featured in Malcom Gladwell's Blink"<<endl;
cout<<""<<endl;
cout<<"Type Rules to View The Rules"<<endl;
cout<<"Or, Type Play to Play The Game"endl;
if (a == "Rules" || a == "rules")
RULES();
if (a == "Play" || a == "play")
SETVALUES();
}

1>------ Build started: Project: Red Blue Card Game, Configuration: Debug Win32 ------
1>Build started 8/21/2011 7:16:10 PM.
1>InitializeBuildStatus:
1> Touching "DebugRed Blue Card Game.unsuccessfulbuild".
1>GenerateTargetFrameworkMonikerAttribute:
1>Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
1>ClCompile:
1> MAIN.cpp
1>MAIN.cpp(17): error C2371: 'd' : redefinition; different basic types
1> MAIN.cpp(13) : see declaration of 'd'
1>MAIN.cpp(34): warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data
1>MAIN.cpp(39): error C2088: '>>' : illegal for class
1>MAIN.cpp(40): error C2088: '==' : illegal for class
1>MAIN.cpp(40): error C2088: '==' : illegal for class
1>MAIN.cpp(41): error C2109: subscript requires array or pointer type
1>MAIN.cpp(44): error C2088: '==' : illegal for class
1>MAIN.cpp(44): error C2088: '==' : illegal for class
1>MAIN.cpp(45): error C2109: subscript requires array or pointer type
1>MAIN.cpp(74): error C2601: 'SETVALUES' : local function definitions are illegal
1> MAIN.cpp(61): this line contains a '{' which has not yet been matched
1>MAIN.cpp(83): error C2601: 'RULES' : local function definitions are illegal
1> MAIN.cpp(61): this line contains a '{' which has not yet been matched
1>MAIN.cpp(107): fatal error C1075: end of file found before the left brace '{' at 'MAIN.cpp(83)' was matched
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:01.20
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Last edited on

Use [code][/code] tags please.

You declare two variables with the identifier ‘d’, one string, another int.

You don’t need a function prototype for main.

Red is not an array (red[r]).

Neither is blue (blue[r]).

You create a couple red and blue arrays (incorrectly) after using the arrays above

1
2
3
4
int red[0] = {-50};
int red[1] = {50}; // red is already declared
int blue[0] = {-100};
int blue[1] = {100}; // as is blue 

play () doesn’t return anything (it should return something of type int).

You are missing a brace at the end of DETERMINE

RULES is missing a brace as well.

system("Pause"); already has a message saying to press any key.

You shouldn’t call main from another function, that is what the return statement is for, to return something from the current function to the function which calls it.

Your post is really messy, so these are the few that stick out to me. If you would place the code in [code][/code] tags and the errors in [output][/output] tags, it would help greatly as it would be much easier to read. Also lessening the capatalized identifiers would be easier on the eyes as well (for me at least).

I have made all the corrections that i understood. Here is the code, i am still getting a few errors

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
#include<iostream>
#include<string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

//Declerations
	//Question Strings
		string a;	//Asking if you want to play
		string b;	//Asking if you want to draw red or blue
		string c;	//Asking if you want to go back to the menu
		string d;	//Asking if you want to play again
	//Variable Declerations
		int r;		//Variable With A Random Value
		int t;		//Variable With Your Total Score
		string x;		//Pick a deck
		int red;	//Prepping Red Matrix
		int blue;	//Prepping Blue Matrix

	//Microprogram Declerations
		int MAIN();
		void PLAY();
		void RULES();
		void DETERMINE();
		void SETVALUES();
		void LOSS();

//---------------------------------------------------------------

//Active Play
void PLAY(){
	system("cls");
	srand ( time(NULL) );
	r = rand() % 1 + 0;
	cout<<"Your total is "<< t <<"!"<<endl;
	cout<<"Pick a deck"<<endl;
	cout<<"Red or Blue"<<endl;
	cin>> x;
	if (x == "Red" || x == "red"){
		t = t + red[r];
		DETERMINE();
	}
	if (x == "Blue" || x == "blue"){
		t = t + blue[r];
		DETERMINE();
	}
	else
		PLAY();
}

//If the player has lost, do this
void loss(){
	system("cls");
	cout<<"You Have Lost"<<endl;
	system("pause");
	return;
}

//Algorithim to determine weather or not the player has been stupid enough to lose a game of luck yet.
void DETERMINE(){
	if (t > 0)
		PLAY();
	if (t == 0 || t < 0)
		LOSS();
	else{
		system("cls");
		cout<<"FATAL SYSTEM ERROR"<<endl;
		system("pause");
		return;
	}
}

//Setting the initials Values
void SETVALUES(){
	t = 500;
	red[0] = {-50};
	red[1] = {50};
	blue[0] = {-100};
	blue[1] = {100};
}

//Telling the player the rules
void RULES(){
	cout<<"The Rules of the game are simple"<<endl;
	cout<<"You start out with 500 dollars"<<endl;
	cout<<"Draw from either the Red or the Blue deck"<<endl;
	cout<<"Each deck has card that either add or subtract from your pool"<<endl;
	cout<<"Have Fun!";
	cout<<"press anykey to go back to the menu"<<endl;
	system("pause");
	return;
}

//Starting Welcome Menu
int MAIN(){
	system("cls");
	cout<<"Welcome to the Red Blue Card Game"<<endl;
	cout<<"Featured in Malcom Gladwell's Blink"<<endl;
	cout<<""<<endl;
	cout<<"Type Rules to View The Rules"<<endl;
	cout<<"Or, Type Play to Play The Game"endl;
	if (a == "Rules" || a == "rules")
		RULES();
	if (a == "Play" || a == "play")
		SETVALUES();
}

1>------ Build started: Project: Red Blue Card Game, Configuration: Debug Win32 ------
1>Build started 8/21/2011 8:39:30 PM.
1>InitializeBuildStatus:
1>  Touching "DebugRed Blue Card Game.unsuccessfulbuild".
1>GenerateTargetFrameworkMonikerAttribute:
1>Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
1>ClCompile:
1>  MAIN.cpp
1>MAIN.cpp(34): warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data
1>MAIN.cpp(41): error C2109: subscript requires array or pointer type
1>MAIN.cpp(45): error C2109: subscript requires array or pointer type
1>MAIN.cpp(77): error C2109: subscript requires array or pointer type
1>MAIN.cpp(77): error C2059: syntax error : '{'
1>MAIN.cpp(77): error C2143: syntax error : missing ';' before '{'
1>MAIN.cpp(77): error C2143: syntax error : missing ';' before '}'
1>MAIN.cpp(78): error C2109: subscript requires array or pointer type
1>MAIN.cpp(78): error C2059: syntax error : '{'
1>MAIN.cpp(78): error C2143: syntax error : missing ';' before '{'
1>MAIN.cpp(78): error C2143: syntax error : missing ';' before '}'
1>MAIN.cpp(79): error C2109: subscript requires array or pointer type
1>MAIN.cpp(79): error C2059: syntax error : '{'
1>MAIN.cpp(79): error C2143: syntax error : missing ';' before '{'
1>MAIN.cpp(79): error C2143: syntax error : missing ';' before '}'
1>MAIN.cpp(80): error C2109: subscript requires array or pointer type
1>MAIN.cpp(80): error C2059: syntax error : '{'
1>MAIN.cpp(80): error C2143: syntax error : missing ';' before '{'
1>MAIN.cpp(80): error C2143: syntax error : missing ';' before '}'
1>MAIN.cpp(102): error C2146: syntax error : missing ';' before identifier 'endl'
1>MAIN.cpp(102): warning C4551: function call missing argument list
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.76
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

And you should note that C++ identifiers are case-sensitive

So even after you fix all your syntax errors, your program will fail to link as the required entry-point will not be found. It must be (all lowercase)

As Danny Toledo said, main does not need a prototype. But MAIN is not main!

And all upper-case identifiers are usually reserved for #defines (and sometimes typedefs). Function names are usually lowercase, lowerCamelCase. or UpperCamelCase (used consistently!).

Andy

P.S. For more info about tags, see «How to use tags»
http://www.cplusplus.com/articles/z13hAqkS/

Last edited on

Errors wrote:
1>MAIN.cpp(41): error C2109: subscript requires array or pointer type
1>MAIN.cpp(45): error C2109: subscript requires array or pointer type
1>MAIN.cpp(77): error C2109: subscript requires array or pointer type (sic)

Your global variable,

red

, is not an array. Therefore, it’s syntactically illegal to use the sub-script ([…]) operator on it.

Errors wrote:
1>MAIN.cpp(77): error C2059: syntax error : ‘{‘
1>MAIN.cpp(77): error C2143: syntax error : missing ‘;’ before ‘{‘
1>MAIN.cpp(77): error C2143: syntax error : missing ‘;’ before ‘}’
1>MAIN.cpp(78): error C2109: subscript requires array or pointer type
1>MAIN.cpp(78): error C2059: syntax error : ‘{‘
1>MAIN.cpp(78): error C2143: syntax error : missing ‘;’ before ‘{‘
1>MAIN.cpp(78): error C2143: syntax error : missing ‘;’ before ‘}’
1>MAIN.cpp(79): error C2109: subscript requires array or pointer type
1>MAIN.cpp(79): error C2059: syntax error : ‘{‘
1>MAIN.cpp(79): error C2143: syntax error : missing ‘;’ before ‘{‘
1>MAIN.cpp(79): error C2143: syntax error : missing ‘;’ before ‘}’
1>MAIN.cpp(80): error C2109: subscript requires array or pointer type
1>MAIN.cpp(80): error C2059: syntax error : ‘{‘
1>MAIN.cpp(80): error C2143: syntax error : missing ‘;’ before ‘{‘
1>MAIN.cpp(80): error C2143: syntax error : missing ‘;’ before ‘}’ (sic)

Braces ({…}) cannot be used in this manner. Braces are only used for initialization lists and body scopes. You need to either remove the braces or replace the braces with parentheses. Also, as I said above, you’ve used

red

as an array, which it is not.

Errors wrote:
1>MAIN.cpp(102): error C2146: syntax error : missing ‘;’ before identifier ‘endl’
1>MAIN.cpp(102): warning C4551: function call missing argument list (sic)

You’ve forgot to place the

<<

before

endl

.

Wazzak

Last edited on

EDIT : wow, I must have forgotten to refresh the page or something; I thought there were no replies to this when I posted, but boy, was I wrong.

No need to duplicate the errors already presented by the above posters

Last edited on

GUYS THANK YOU SO MUCH FOR ALL YOUR HELP. THERES JUST A LITTLE BIT LEFT. ONLY ONE TYPE OF ERROR.

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
#include<iostream>
#include<string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

//Declerations
	//Question Strings
		string a;	//Asking if you want to play
		string b;	//Asking if you want to draw red or blue
		string c;	//Asking if you want to go back to the menu
		string d;	//Asking if you want to play again
	//Variable Declerations
		int r;		//Variable With A Random Value
		int t;		//Variable With Your Total Score
		string x;		//Pick a deck
		int red;	//Prepping Red Matrix
		int blue;	//Prepping Blue Matrix

	//Microprogram Declerations
		int main();
		void play();
		void rules();
		void determine();
		void setvalues();
		void loss();

//---------------------------------------------------------------

//Active Play
void play(){
	system("cls");
	srand ( time(NULL) );
	r = rand() % 1 + 0;
	cout<<"Your total is "<< t <<"!"<<endl;
	cout<<"Pick a deck"<<endl;
	cout<<"Red or Blue"<<endl;
	cin>> x;
	if (x == "Red" || x == "red"){
		t = t + red[r];
		determine();
	}
	if (x == "Blue" || x == "blue"){
		t = t + blue[r];
		determine();
	}
	else
		play();
}

//If the player has lost, do this
void loss(){
	system("cls");
	cout<<"You Have Lost"<<endl;
	system("pause");
	return;
}

//Algorithim to determine weather or not the player has been stupid enough to lose a game of luck yet.
void determine(){
	if (t > 0)
		play();
	if (t == 0 || t < 0)
		loss();
	else{
		system("cls");
		cout<<"FATAL SYSTEM ERROR"<<endl;
		system("pause");
		return;
	}
}

//Setting the initials Values
void setvalues(){
	t = 500;
	red[0] = -50;
	red[1] = 50;
	blue[0] = -100;
	blue[1] = 100;
}

//Telling the player the rules
void rules(){
	cout<<"The Rules of the game are simple"<<endl;
	cout<<"You start out with 500 dollars"<<endl;
	cout<<"Draw from either the Red or the Blue deck"<<endl;
	cout<<"Each deck has card that either add or subtract from your pool"<<endl;
	cout<<"Have Fun!";
	cout<<"press anykey to go back to the menu"<<endl;
	system("pause");
	return;
}

//Starting Welcome Menu
int main(){
	system("cls");
	cout<<"Welcome to the Red Blue Card Game"<<endl;
	cout<<"Featured in Malcom Gladwell's Blink"<<endl;
	cout<<""<<endl;
	cout<<"Type Rules to View The Rules"<<endl;
	cout<<"Or, Type Play to Play The Game"<<endl;
	if (a == "Rules" || a == "rules")
		rules();
	if (a == "Play" || a == "play")
		setvalues();
}

[output]
1>—— Build started: Project: Red Blue Card Game, Configuration: Debug Win32 ——
1>Build started 8/21/2011 9:10:03 PM.
1>InitializeBuildStatus:
1> Touching «DebugRed Blue Card Game.unsuccessfulbuild».
1>GenerateTargetFrameworkMonikerAttribute:
1>Skipping target «GenerateTargetFrameworkMonikerAttribute» because all output files are up-to-date with respect to the input files.
1>ClCompile:
1> MAIN.cpp
1>MAIN.cpp(34): warning C4244: ‘argument’ : conversion from ‘time_t’ to ‘unsigned int’, possible loss of data
1>MAIN.cpp(41): error C2109: subscript requires array or pointer type
1>MAIN.cpp(45): error C2109: subscript requires array or pointer type
1>MAIN.cpp(77): error C2109: subscript requires array or pointer type
1>MAIN.cpp(78): error C2109: subscript requires array or pointer type
1>MAIN.cpp(79): error C2109: subscript requires array or pointer type
1>MAIN.cpp(80): error C2109: subscript requires array or pointer type
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.64
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

[output]

red

is not an array. You need to declare it as an array at the point of declaration. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Declare an array of 3 integers and initialize each element
// with a random value (hand picked).
int Red[3] = 
{
    37, 29, 28
};

int main( )
{
    // Use the sub-script operator ([...]) to access individual
    // elements of the array.
    Red[0] = 10;
}

Note that indices are zero-based. This means that the first index (first element) is 0, the second is 1, and so on.

Wazzak

Last edited on

its no longer giving me errors messages, but it shuts down immediately before escaping main
heres a copy of main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(){
	system("cls");
	cout<<"Welcome to the Red Blue Card Game"<<endl;
	cout<<"Featured in Malcom Gladwell's Blink"<<endl;
	cout<<""<<endl;
	cout<<"Type Rules to View The Rules"<<endl;
	cout<<"Or, Type Play to Play The Game"<<endl;
	if (a == "Rules" || a == "rules")
		rules();
	if (a == "Play" || a == "play")
		setvalues();
	else
		main();
}

That’s because you need to explicitly tell the program to wait. You can do this with either function:

1
2
3
4
5
int Wait( )
{
    std::cin.ignore( std::numeric_limits< std::streamsize >::max( ), 'n' );
    return 0;
}

Or

1
2
3
4
5
int Wait( )
{
    std::cin.get( );
    return 0;
}

The first option requires the user to press enter. The second option requires the user to enter a character then press enter. The choice is yours.

A final note: Never call

main( )

. Only the operating system should call

main( )

.

Wazzak

That’s because there’s no chance for the user to input anything. You need a cin statement to get «rules» or «play»

How does that compile? When I call main () in main, I get:

Error E2120 main.cpp 6: Cannot call 'main' from within the program in function main()

If I try calling it from another function, I get the same error, only «main ()» is replaced by the name of the function trying to call it.

As it has already been stated, you need to get input from the user to determine whether he/ she wants to play or see the rules.

cin.get (); only requires the user to hit enter. If you are getting input data before the use of the function (cin>> and getline as well I think), use cin.clear (); or cin.sync (); (or both) before cin.get ();

A quick jump back to the full code, there is also no need for function prototypes if you define the functions before main (or whatever function will be calling it).

Last edited on

Danny,

std::cin.clear( )

only clears the flags set by

std::cin

; it doesn’t actually manipulate the characters within the stream.

I do admit, however, that I was wrong about

std::cin.get( )

.

Wazzak

Topic archived. No new replies allowed.

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

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

  • Error c2086 redefinition
  • Error c2084 функция int main void уже имеет текст реализации
  • Error c2082 переопределение формального параметра
  • Error c2078 слишком много инициализаторов
  • Error c2078 too many initializers

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

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