0 / 0 / 0 Регистрация: 16.07.2016 Сообщений: 23 |
|
1 |
|
26.07.2016, 13:00. Показов 8923. Ответов 12
Доброго времени суток
__________________
0 |
257 / 234 / 185 Регистрация: 02.04.2016 Сообщений: 898 |
|
26.07.2016, 13:05 |
2 |
Кидай сюда код.
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 |
|||
код очень большой
0 |
Объявлятель переменных 1199 / 389 / 315 Регистрация: 24.09.2011 Сообщений: 1,232 |
|
26.07.2016, 14:03 |
5 |
Пробовали тот же код с использованием
1 |
0 / 0 / 0 Регистрация: 16.07.2016 Сообщений: 23 |
|
26.07.2016, 14:11 [ТС] |
6 |
ну со switch я не пробовал
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 |
ошибка появляется во время компиляции Я честно пытался найти в приведённом выше коде 493 строку, но не преуспел.
1 |
0 / 0 / 0 Регистрация: 16.07.2016 Сообщений: 23 |
|
26.07.2016, 15:14 [ТС] |
11 |
я не программист пока что не те знания Добавлено через 2 минуты Добавлено через 20 минут
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 |
|||
Если синтаксис подсветить, то всё становится очевидным.
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>------ 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
|
|
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>------ 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.
|
|
[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]
is not an array. You need to declare it as an array at the point of declaration. For example:
|
|
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
|
|
That’s because you need to explicitly tell the program to wait. You can do this with either function:
|
|
Or
|
|
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.