Oleg Pridarun 2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
||||
1 |
||||
02.07.2017, 13:05. Показов 7161. Ответов 12 Метки using namespace, visual studio, с, Синтаксис (Все метки)
У меня есть заголовочный файл LanguageEng.h В нём находится код:
При компиляции программы с этим заголовочным файлом происходит ошибка: c:users***onedriveпрограммыgamelanguageeng.h(4): error C2143: синтаксическая ошибка: отсутствие «;» перед «using namespace»
0 |
1642 / 1091 / 487 Регистрация: 17.07.2012 Сообщений: 5,345 |
|
02.07.2017, 13:53 |
2 |
Код программы в студию.
0 |
223 / 213 / 80 Регистрация: 26.04.2013 Сообщений: 972 |
|
02.07.2017, 14:08 |
3 |
Попробуйте добавить
0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
02.07.2017, 14:14 [ТС] |
4 |
Код программы в студию. Давайте я лучше весь проект кину, так как он многофайловый Добавлено через 5 минут
Попробуйте добавить Проблема осталась та же. Ни каких изменений
0 |
3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
02.07.2017, 16:40 |
5 |
Давайте я лучше весь проект кину И где же он?
0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
02.07.2017, 17:21 [ТС] |
6 |
И где же он? Хотел поместить его на гугл диск, но это, похоже заняло бы несколько часов (не знаю по какой причине). Скинуть код из файла с int main()?
0 |
3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
02.07.2017, 17:24 |
7 |
Хотел поместить его на гугл диск, но это, похоже заняло бы несколько часов (не знаю по какой причине). Здесь, в архиве, выложи. Или очень большой? Добавлено через 59 секунд
Скинуть код из файла с int main()? Хедеры, с определениями классов, есть в проекте?
0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
02.07.2017, 20:42 [ТС] |
8 |
Здесь, в архиве, выложи. Или очень большой? Добавлено через 59 секунд Хедеры, с определениями классов, есть в проекте? Классы не использовал. Я в них пока не разобрался. На данный момент только функции и переменные в хедерах
0 |
3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
02.07.2017, 20:56 |
9 |
Выкладывать проект будешь, или можно отписываться от темы?
0 |
5230 / 3202 / 362 Регистрация: 12.12.2009 Сообщений: 8,112 Записей в блоге: 2 |
|
03.07.2017, 15:11 |
10 |
нужно смотреть на файл, который инклюдит LanguageEng.h
0 |
с++ 1282 / 523 / 225 Регистрация: 15.07.2015 Сообщений: 2,562 |
|
03.07.2017, 15:18 |
11 |
так в этом файле и исправляй ошибку по пути так как LanguageEng.h и такой languageeng.h это разные файлы или нет?
0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
05.07.2017, 22:50 [ТС] |
12 |
Простите, мне отключили интернет. Проблему решил. languageeng и LanguageEng для Visual у меня одно и тоже. Проблема была в другом хедере. В нём была пропущена ;, и другие хедеры на это реагировали
0 |
Заблокирован |
|
05.07.2017, 23:01 |
13 |
Решение
Проблема была в другом хедере. Это было сразу очевидно.
1 |
this is my header:
#ifndef HEADER_H
#define HEADER_H
class Math
{
private:
static enum names {amin = 27 , ali = 46};
public:
static void displayMessage();
}
#endif // HEADER_H
and this is the header definition:
#include <iostream>
#include <iomanip>
#include "Header.h"
using namespace std;
void Math::displayMessage()
{
cout<<amin<<setw(5)<<ali<<endl;
}
and this is the main:
#include <iostream>
#include "Header.h"
using namespace std;
enum Math::names;
int main()
{
Math::displayMessage();
}
i got these errors:
error C2143: syntax error : missing ';' before 'using'
error C2143: syntax error : missing ';' before 'using'
one of them is for main and the other is for header definition,
i have encountered several time in my programming,
could explain that for me in this situation,
please help me
best regards
Amin khormaei
codemania
1,0981 gold badge9 silver badges26 bronze badges
asked Feb 27, 2014 at 7:23
2
After preprocessing, your source code[1] for your «header definition» becomes like
// iostream contents
// iomanip contents
class Math
{
private:
static enum names {amin = 27 , ali = 46};
public:
static void displayMessage();
}
using namespace std;
void Math::displayMessage()
{
cout<<amin<<setw(5)<<ali<<endl;
}
Let’s now see error C2143: syntax error : missing ';' before 'using'
. Where is using
in the above code? What is it before using
?
}
^ This
using namespace std;
Because of the part of the error that says missing ';'
, we must add that missing ;
.
};
^
[1] More precisely called a «translation unit».
answered Feb 27, 2014 at 7:27
Mark GarciaMark Garcia
17.4k4 gold badges57 silver badges94 bronze badges
0
You’re missing a ;
after the definition of class Math
.
answered Feb 27, 2014 at 7:23
Mike SeymourMike Seymour
249k28 gold badges447 silver badges639 bronze badges
missing ‘;’ before ‘using’
Just read what it tells you. There is a missing ; before using
. Then look at your code, where did you use using
? (the compiler likely told you the line)
#include "Header.h"
using namespace std;
What’s before using
? The header include.
The compiler most likely goes through your code in a linear manner, so what it did when it saw #include "Header.h"
was to go through that file. Meaning that the error will be the very end of «Header.h». And indeed, there is a missing ; at the end of the class declaration, just like the compiler told you.
answered Feb 27, 2014 at 7:30
LundinLundin
192k39 gold badges251 silver badges392 bronze badges
это мой заголовок:
#ifndef HEADER_H
#define HEADER_H
class Math
{
private:
static enum names {amin = 27 , ali = 46};
public:
static void displayMessage();
}#endif // HEADER_H
и это определение заголовка:
#include <iostream>
#include <iomanip>
#include "Header.h"
using namespace std;
void Math::displayMessage()
{
cout<<amin<<setw(5)<<ali<<endl;
}
и это главное:
#include <iostream>
#include "Header.h"
using namespace std;
enum Math::names;
int main()
{
Math::displayMessage();
}
я получил эти ошибки:
error C2143: syntax error : missing ';' before 'using'
error C2143: syntax error : missing ';' before 'using'
один из них для основного, а другой для определения заголовка,
я встречался несколько раз в моем программировании,
мог бы объяснить, что для меня в этой ситуации,
Помогите мне, пожалуйста
с уважением
Амин Хормаи
8
Решение
После предварительной обработки ваш исходный код[1] для вашего «определение заголовка» становится как
// iostream contents
// iomanip contentsclass Math
{
private:
static enum names {amin = 27 , ali = 46};
public:
static void displayMessage();
}
using namespace std;
void Math::displayMessage()
{
cout<<amin<<setw(5)<<ali<<endl;
}
Давай теперь посмотрим error C2143: syntax error : missing ';' before 'using'
, Где using
в приведенном коде? Что это раньше using
?
}
^ This
using namespace std;
Из-за части ошибки, которая говорит missing ';'
Надо добавить что пропало ;
,
};
^
[1] Точнее, называется «единица перевода».
13
Другие решения
Вы скучаете по ;
после определения class Math
,
6
отсутствует ‘;’ Перед использованием’
Просто прочитайте, что это говорит вам. Отсутствует; до using
, Тогда посмотрите на свой код, где вы использовали using
? (компилятор, вероятно, сказал вам строку)
#include "Header.h"
using namespace std;
Что раньше using
? Заголовок включает.
Компилятор, скорее всего, просматривает ваш код линейно, так что он сделал, когда увидел #include "Header.h"
должен был пройти через этот файл. Это означает, что ошибка будет самым концом «Header.h». И действительно, здесь отсутствует; в конце объявления класса, как сказал вам компилятор.
0
|
|
|
Компилятор не в себе
, глючит.. выдаёт ошибку там, где её быть не должно
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
после попытки компиляции программы в MVisual C++ 2008 Express пишет следующие тупые ошибки: Ошибка 1 error C2143: синтаксическая ошибка: отсутствие «;» перед «using» Ошибка 2 error C2628: недопустимый ‘Temperature’ с последующим ‘void’ (возможно, отсутствует ‘;’) //gradus.h #pragma once #include <iostream> #include <string> using namespace std; class Temperature { private: int grad; char sys; public: Temperature(int gr = 0 , char shkala = ‘C’) : grad(gr) , sys(shkala) {}; void set( int gr , char shkala) {grad = gr; sys = shkala;}; void set( string str); int change(); void show(); } //gradus.cpp #include «gradus.h» void Temperature::set(string str) {…} int Temperature::change() {…} void Temperature::show() {…} |
kanes |
|
При определении класса после } ставят ; |
Potroshitell |
|
аа.. сори, не компилятор глючит, а я! вопрос в топку Сообщение отредактировано: Potroshitell — 15.01.10, 13:46 |
kanes |
|
Цитата Potroshitell @ 15.01.10, 13:45 ааа, или возможно просто set — ключевое слово. не ключевое, но слово обозначающее контейнер из STL std::set, правда для него требуется заголовок <set> так что дело не в этом |
Potroshitell |
|
я ещё вот хотел бы задать 1 мини-вопросик.. ради него наверно не стоит создавать отдельную тему=) class Temperature { public: Temperature(int gr = 0 , char shkala = ‘C’) : grad(gr) , sys(shkala) {}; void set( int gr , char shkala) {grad = gr; sys = shkala;} /* вот тут. если функция определяется в классе как встроенная, то нужно ставить ; после } ? а то компилятор вроде не ругается в обоих случаях. */ … Сообщение отредактировано: Potroshitell — 15.01.10, 14:08 |
zim22 |
|
Junior Рейтинг (т): 3 |
Цитата Potroshitell @ 15.01.10, 14:07 если функция определяется в классе как встроенная, то нужно ставить ; после } ? не нужно. |
Potroshitell |
|
Mr.Delphist |
|
И это… того… Не пиши «using namespace» в заголовочных файлах, а то это очень «добрый» сюрприз себе на будущее |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ Script execution time: 0,0322 ] [ 16 queries used ] [ Generated: 3.06.23, 22:36 GMT ]
I am VERY new to C++ and Open GL and I have been trying to display 3D objects in a scene. it worked fine with one but when I tried to alter my code to add a second, my code regarding the HUD text showing the camera location started giving errors. The error above is shown and it is apparently in the sstream file (#include). I have tried searching around and asking for help but there is nothing that helps/that I understand. When I comment-out the #include line and the code that uses it, I get a similar saying «error C2143: syntax error : missing ‘;’ before ‘using’» in my main.cpp file.
I am running Visual Studio 2010 and I have even tried turning the whole thing off and on again, and copying the code over to a new project. Help would be greatly appreciated.
#include <Windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glut.h"
#include "SceneObject.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
//#include <cmath>
//#include <limits>
//#include <cstdlib>
using namespace std;
…
stringstream ss;
ss << "Camera (" << cam.pos.x << ", " << cam.pos.y << ", " << cam.pos.z << ")";
glClear(GL_DEPTH_BUFFER_BIT);
outputText(-1.0, 0.5, ss.str());
…
#ifndef SCENEOBJECT_H
#define SCENEOBJECT_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
struct point3D {
float x;
float y;
float z;
};
struct colour{
float r;
float g;
float b;
};
struct tri {
int a;
int b;
int c;
};
class SceneObject {
private:
int NUM_VERTS;
int NUM_COL;
int NUM_TRI;
point3D * vertices;
colour * colours;
tri * indices;
void drawTriangle(int a, int b, int c);
public:
SceneObject(const string fName) {
read_file(fName);
}
void drawShape()
{
// DO SOMETHING HERE
}
int read_file (const string fileName)
{
ifstream inFile;
inFile.open(fileName);
if (!inFile.good())
{
cerr << "Can't open file" << endl;
NUM_TRI = 0;
return 1;
}
//inFile >> shapeID;
inFile >> NUM_VERTS;
vertices = new point3D[NUM_VERTS];
for (int i=0; i < NUM_VERTS; i++)
{
inFile >> vertices[i].x;
inFile >> vertices[i].y;
inFile >> vertices[i].z;
}
inFile >> NUM_COL;
//inFile >> randomCol;
colours = new colour[NUM_COL];
/*if (randomCol == 'y')
{
for (int i=0; i < NUM_COL; i++)
{
colours[i].r = ((float) rand() / (RAND_MAX+1));
colours[i].g = ((float) rand() / (RAND_MAX+1));
colours[i].b = ((float) rand() / (RAND_MAX+1));
}
}
else if (randomCol == 'n')
{*/
for (int i=0; i < NUM_COL; i++)
{
inFile >> colours[i].r;
inFile >> colours[i].g;
inFile >> colours[i].b;
}
//}
inFile >> NUM_TRI;
indices = new tri[NUM_TRI];
for (int i=0; i < NUM_TRI; i++)
{
inFile >> indices[i].a;
inFile >> indices[i].b;
inFile >> indices[i].c;
}
inFile.close();
return 0;
}
}
#endif
I haven’t changed the code and as far as I am aware, there are semi-colons where there are meant to be. Even my friend who has been programming for 5 years couldn’t solve this. I will include any other specific code if needed. And when I said new to C++ and OpenGL I really much VERY new.
This is even my first post. I’ll get there eventually.
Oleg Pridarun 2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
||||
1 |
||||
02.07.2017, 13:05. Показов 6610. Ответов 12 Метки using namespace, visual studio, с, Синтаксис (Все метки)
У меня есть заголовочный файл LanguageEng.h В нём находится код:
При компиляции программы с этим заголовочным файлом происходит ошибка: c:users***onedriveпрограммыgamelanguageeng.h (4): error C2143: синтаксическая ошибка: отсутствие «;» перед «using namespace»
__________________ 0 |
1642 / 1091 / 487 Регистрация: 17.07.2012 Сообщений: 5,345 |
|
02.07.2017, 13:53 |
2 |
Код программы в студию. 0 |
223 / 213 / 80 Регистрация: 26.04.2013 Сообщений: 972 |
|
02.07.2017, 14:08 |
3 |
Попробуйте добавить 0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
02.07.2017, 14:14 [ТС] |
4 |
Код программы в студию. Давайте я лучше весь проект кину, так как он многофайловый Добавлено через 5 минут
Попробуйте добавить Проблема осталась та же. Ни каких изменений 0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
02.07.2017, 16:40 |
5 |
Давайте я лучше весь проект кину И где же он? 0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
02.07.2017, 17:21 [ТС] |
6 |
И где же он? Хотел поместить его на гугл диск, но это, похоже заняло бы несколько часов (не знаю по какой причине). Скинуть код из файла с int main()? 0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
02.07.2017, 17:24 |
7 |
Хотел поместить его на гугл диск, но это, похоже заняло бы несколько часов (не знаю по какой причине). Здесь, в архиве, выложи. Или очень большой? Добавлено через 59 секунд
Скинуть код из файла с int main()? Хедеры, с определениями классов, есть в проекте? 0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
02.07.2017, 20:42 [ТС] |
8 |
Здесь, в архиве, выложи. Или очень большой? Добавлено через 59 секунд Хедеры, с определениями классов, есть в проекте? Классы не использовал. Я в них пока не разобрался. На данный момент только функции и переменные в хедерах 0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
02.07.2017, 20:56 |
9 |
Выкладывать проект будешь, или можно отписываться от темы? 0 |
5224 / 3196 / 362 Регистрация: 12.12.2009 Сообщений: 8,101 Записей в блоге: 2 |
|
03.07.2017, 15:11 |
10 |
нужно смотреть на файл, который инклюдит LanguageEng.h 0 |
с++ 1282 / 523 / 225 Регистрация: 15.07.2015 Сообщений: 2,562 |
|
03.07.2017, 15:18 |
11 |
так в этом файле и исправляй ошибку по пути так как LanguageEng.h и такой languageeng.h это разные файлы или нет? 0 |
2 / 2 / 1 Регистрация: 16.06.2016 Сообщений: 91 |
|
05.07.2017, 22:50 [ТС] |
12 |
Простите, мне отключили интернет. Проблему решил. languageeng и LanguageEng для Visual у меня одно и тоже. Проблема была в другом хедере. В нём была пропущена ;, и другие хедеры на это реагировали 0 |
Заблокирован |
|
05.07.2017, 23:01 |
13 |
Решение
Проблема была в другом хедере. Это было сразу очевидно. 1 |
I am extremely confused why I am getting this strange error all the sudden:
Time.h is a very simple class, and it has a semicolon at the end of the class description, so I am pretty sure my code is correct here.. Then I get the same errors in: Microsoft Visual Studio 10.0VCincludememory.. Any ideas!?!? Thanks!
Compiler Output
1>ClCompile:
1> Stop.cpp
1>c:projectnextbusTime.h(17): error C2143: syntax error : missing ';' before 'using'
1>c:projectnextbusTime.h(17): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1> NextBusDriver.cpp
1>C:Program Files (x86)Microsoft Visual Studio 10.0VCincludememory(16): error C2143: syntax error : missing ';' before 'namespace'
1>C:Program Files (x86)Microsoft Visual Studio 10.0VCincludememory(16): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Update:
Can’t really post all the code as this is for a school project and we aren’t supposed to post before we submit, but small snippets should be ok..
Time.h
#ifndef TIME_HPP
#define TIME_HPP
#include <string>
#include <sstream>
using namespace std;
class Time {
// Defines a time in a 24 hour clock
public:
// Time constructor
Time(int hours = 0 , int minutes= 0);
// POST: Set hours int
void setHours(int h);
// POST: Set minutes int
void setMinutes(int m);
// POST: Returns hours int
int getHours();
// POST: Returns minutes int
int getMinutes();
// POST: Returns human readable string describing the time
// This method can be overridden in inheriting classes, so should be virtual so pointers will work as desired
string toString();
private:
string intToString(int num);
// POST: Converts int to string type
int hours_;
int minutes_;
};
#endif
DepartureTime.h (inherited class)
#ifndef DEPARTURE_TIME_HPP
#define DEPARTURE_TIME_HPP
#include <string>
#include "Time.h"
using namespace std;
class DepartureTime: public Time {
public:
// Departure Time constructor
DepartureTime(string headsign, int hours=0, int minutes=0) : Time(hours, minutes), headsign_(headsign) { }
// POST: Returns bus headsign
string getHeadsign();
// POST: Sets the bus headsign
void setHeadsign(string headsign);
// POST: Returns human readable string describing the departure
string toString();
private:
// Class variables
string headsign_;
};
#endif
I am extremely confused why I am getting this strange error all the sudden:
Time.h is a very simple class, and it has a semicolon at the end of the class description, so I am pretty sure my code is correct here.. Then I get the same errors in: Microsoft Visual Studio 10.0VCincludememory.. Any ideas!?!? Thanks!
Compiler Output
1>ClCompile:
1> Stop.cpp
1>c:projectnextbusTime.h(17): error C2143: syntax error : missing ';' before 'using'
1>c:projectnextbusTime.h(17): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1> NextBusDriver.cpp
1>C:Program Files (x86)Microsoft Visual Studio 10.0VCincludememory(16): error C2143: syntax error : missing ';' before 'namespace'
1>C:Program Files (x86)Microsoft Visual Studio 10.0VCincludememory(16): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Update:
Can’t really post all the code as this is for a school project and we aren’t supposed to post before we submit, but small snippets should be ok..
Time.h
#ifndef TIME_HPP
#define TIME_HPP
#include <string>
#include <sstream>
using namespace std;
class Time {
// Defines a time in a 24 hour clock
public:
// Time constructor
Time(int hours = 0 , int minutes= 0);
// POST: Set hours int
void setHours(int h);
// POST: Set minutes int
void setMinutes(int m);
// POST: Returns hours int
int getHours();
// POST: Returns minutes int
int getMinutes();
// POST: Returns human readable string describing the time
// This method can be overridden in inheriting classes, so should be virtual so pointers will work as desired
string toString();
private:
string intToString(int num);
// POST: Converts int to string type
int hours_;
int minutes_;
};
#endif
DepartureTime.h (inherited class)
#ifndef DEPARTURE_TIME_HPP
#define DEPARTURE_TIME_HPP
#include <string>
#include "Time.h"
using namespace std;
class DepartureTime: public Time {
public:
// Departure Time constructor
DepartureTime(string headsign, int hours=0, int minutes=0) : Time(hours, minutes), headsign_(headsign) { }
// POST: Returns bus headsign
string getHeadsign();
// POST: Sets the bus headsign
void setHeadsign(string headsign);
// POST: Returns human readable string describing the departure
string toString();
private:
// Class variables
string headsign_;
};
#endif
- Remove From My Forums
-
Question
-
/* FeetToMeters.cpp : Demonstrates a conversion program that uses a decimal point value */ #include "stdafx.h" #include <iostream> using namespace std; int main() { // Define the variables double f; // holds the value of "feet" double m; // holds the value of "meters" // Get the lenfth to calculate from the user cout << "Enter The value in Feet: "; cin >> f; cout << "n"; // new line // Convert to meters using the formula m = f / 3.28; // This is the formula cout << f << " Feet Is Equal To " << m << " metersn"; return 0; }Ok.. so I decide to start learning some inteligence <c++> and start in Visual C++ latest down load, get the turorials suggested which are great and get cracking at it.
After the fourth lesson I get the following build error
c:program filesmicrosoft visual studio 9.0vcincludeistream(13) : error C2143: syntax error : missing ‘;’ before ‘namespace’
the only difference with the various lesson projects I have been working on is the actual code
int main()
{
code…..
code…
return 0
}after typing the attached code I am unable to build all previous project lessons, I did the whole reboot thing and still the same problem?
|
|
|
Компилятор не в себе
, глючит.. выдаёт ошибку там, где её быть не должно
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
после попытки компиляции программы в MVisual C++ 2008 Express пишет следующие тупые ошибки: Ошибка 1 error C2143: синтаксическая ошибка: отсутствие «;» перед «using» Ошибка 2 error C2628: недопустимый ‘Temperature’ с последующим ‘void’ (возможно, отсутствует ‘;’) //gradus.h #pragma once #include <iostream> #include <string> using namespace std; class Temperature { private: int grad; char sys; public: Temperature(int gr = 0 , char shkala = ‘C’) : grad(gr) , sys(shkala) {}; void set( int gr , char shkala) {grad = gr; sys = shkala;}; void set( string str); int change(); void show(); } //gradus.cpp #include «gradus.h» void Temperature::set(string str) {…} int Temperature::change() {…} void Temperature::show() {…} |
kanes |
|
При определении класса после } ставят ; |
Potroshitell |
|
аа.. сори, не компилятор глючит, а я! вопрос в топку Сообщение отредактировано: Potroshitell — 15.01.10, 13:46 |
kanes |
|
Цитата Potroshitell @ 15.01.10, 13:45 ааа, или возможно просто set — ключевое слово. не ключевое, но слово обозначающее контейнер из STL std::set, правда для него требуется заголовок <set> так что дело не в этом |
Potroshitell |
|
я ещё вот хотел бы задать 1 мини-вопросик.. ради него наверно не стоит создавать отдельную тему=) class Temperature { public: Temperature(int gr = 0 , char shkala = ‘C’) : grad(gr) , sys(shkala) {}; void set( int gr , char shkala) {grad = gr; sys = shkala;} /* вот тут. если функция определяется в классе как встроенная, то нужно ставить ; после } ? а то компилятор вроде не ругается в обоих случаях. */ … Сообщение отредактировано: Potroshitell — 15.01.10, 14:08 |
zim22 |
|
Junior Рейтинг (т): 3 |
Цитата Potroshitell @ 15.01.10, 14:07 если функция определяется в классе как встроенная, то нужно ставить ; после } ? не нужно. |
Potroshitell |
|
Mr.Delphist |
|
И это… того… Не пиши «using namespace» в заголовочных файлах, а то это очень «добрый» сюрприз себе на будущее |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ Script execution time: 0,0695 ] [ 16 queries used ] [ Generated: 31.01.23, 02:10 GMT ]
Я ОЧЕНЬ новичок в C ++ и Open GL, и я пытался отображать 3D-объекты в сцене. с одним он работал нормально, но когда я попытался изменить свой код, чтобы добавить второй, мой код, касающийся текста HUD, показывающего местоположение камеры, начал выдавать ошибки. Показана указанная выше ошибка, очевидно, в файле sstream (#include). Я пробовал искать и просить о помощи, но ничего не помогло / что я понял. Когда я закомментирую строку #include и код, который ее использует, я получаю аналогичное высказывание «ошибка C2143: синтаксическая ошибка: отсутствует»; перед «использованием» «в моем файле main.cpp.
Я использую Visual Studio 2010, и я даже попытался выключить и снова включить все это и скопировать код в новый проект. Помощь будет принята с благодарностью.
#include <Windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glut.h"
#include "SceneObject.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
//#include <cmath>
//#include <limits>
//#include <cstdlib>
using namespace std;
…
stringstream ss;
ss << "Camera (" << cam.pos.x << ", " << cam.pos.y << ", " << cam.pos.z << ")";
glClear(GL_DEPTH_BUFFER_BIT);
outputText(-1.0, 0.5, ss.str());
…
#ifndef SCENEOBJECT_H
#define SCENEOBJECT_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
struct point3D {
float x;
float y;
float z;
};
struct colour{
float r;
float g;
float b;
};
struct tri {
int a;
int b;
int c;
};
class SceneObject {
private:
int NUM_VERTS;
int NUM_COL;
int NUM_TRI;
point3D * vertices;
colour * colours;
tri * indices;
void drawTriangle(int a, int b, int c);
public:
SceneObject(const string fName) {
read_file(fName);
}
void drawShape()
{
// DO SOMETHING HERE
}
int read_file (const string fileName)
{
ifstream inFile;
inFile.open(fileName);
if (!inFile.good())
{
cerr << "Can't open file" << endl;
NUM_TRI = 0;
return 1;
}
//inFile >> shapeID;
inFile >> NUM_VERTS;
vertices = new point3D[NUM_VERTS];
for (int i=0; i < NUM_VERTS; i++)
{
inFile >> vertices[i].x;
inFile >> vertices[i].y;
inFile >> vertices[i].z;
}
inFile >> NUM_COL;
//inFile >> randomCol;
colours = new colour[NUM_COL];
/*if (randomCol == 'y')
{
for (int i=0; i < NUM_COL; i++)
{
colours[i].r = ((float) rand() / (RAND_MAX+1));
colours[i].g = ((float) rand() / (RAND_MAX+1));
colours[i].b = ((float) rand() / (RAND_MAX+1));
}
}
else if (randomCol == 'n')
{*/
for (int i=0; i < NUM_COL; i++)
{
inFile >> colours[i].r;
inFile >> colours[i].g;
inFile >> colours[i].b;
}
//}
inFile >> NUM_TRI;
indices = new tri[NUM_TRI];
for (int i=0; i < NUM_TRI; i++)
{
inFile >> indices[i].a;
inFile >> indices[i].b;
inFile >> indices[i].c;
}
inFile.close();
return 0;
}
}
#endif
Я не менял код, и, насколько мне известно, там, где они должны быть, есть точки с запятой. Даже мой друг, который занимается программированием 5 лет, не смог решить эту проблему. При необходимости я добавлю любой другой конкретный код. И когда я сказал «новичок» в C ++ и OpenGL, я действительно ОЧЕНЬ новичок. Это даже мой первый пост. В конце концов я доберусь туда.
Перейти к контенту
Solved
When I try to compile this program i keep getting these errors:
(50) : error C2059: syntax error :
‘<=’(50) : error C2143: syntax error
: missing ‘;’ before ‘{‘(51) : error
C2059: syntax error : ‘>’(51) : error
C2143: syntax error : missing ‘;’
before ‘{‘(62) : error C2059: syntax
error : ‘else’(62) : error C2143:
syntax error : missing ‘;’ before ‘{‘
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
class income {
private:
double incm;
double subtract;
double taxRate;
double add;
char status;
public:
void setStatus ( char stats ) { status = stats; }
void setIncm (double in ) { incm = in; }
void setSubtract ( double sub ) { subtract = sub; }
void setTaxRate ( double rate ) { taxRate = rate; }
void setAdd ( double Add ) { add = Add; }
char getStatus () { return status; }
double getIncm () { return incm; }
double getsubtract () { return subtract; }
double getTaxRate () { return taxRate; }
double getAdd () { return add; }
void calcIncome ();
};
//calcIncome
int main () {
income _new;
double ajIncome = 0, _incm = 0;
char status = ' ';
bool done = false;
while ( !done ) {
cout << "Please enter your TAXABLE INCOME:n" << endl;
cin >> _incm;
if(cin.fail()) { cin.clear(); }
if ( _incm <= 0) { cout << "the income must be greater than 0... n" << endl; }
if ( _incm > 0) { done = true; _new.setIncm(_incm); }
}
done = false;
char stt [2] = " ";
while ( !done ) {
cout << "Please declare weather you are filing taxes jointly or single" << "n";
cout << "t's' = singlent'm' = married" << endl;
cin >> stt;
if(cin.fail()) { cin.clear(); }
if ( status == 's' || status == 'm' ) { done = true; _new.setStatus(stt[0]); }
//if else { }
}
return 0;
};
This is part of a homework assignment so any pointers on bettering my programing would be **great**
Note:I am using Windows 7 with VS express C++ 2008
asked Jan 13, 2010 at 15:44
WallterWallter
4,2656 gold badges29 silver badges33 bronze badges
3
income
is the name of your class. _incm
is the name of your variable. Perhaps you meant this (notice the use of _incm
not income
):
if (_incm <= 0) { cout << "the income must be greater than 0... n" << endl; }
if (_incm > 0) { done = true; _new.setIncm(_incm); }
Frequently you use CamelCase for class names and lowercase for instance variable names. Since C++ is case-sensitive, they wouldn’t conflict each other if they use different case.
answered Jan 13, 2010 at 15:47
Jon-EricJon-Eric
16.7k9 gold badges64 silver badges96 bronze badges
Your variable is named incom
, not income
. income
refers to a type, so the compiler gets confused and you get a syntax error when you try to compare that type against a value in line 50.
One note for bettering you programming would be to use more distinct variable names to avoid such confusions…
answered Jan 13, 2010 at 15:46
sthsth
218k53 gold badges277 silver badges364 bronze badges
1
BeyB 0 / 0 / 0 Регистрация: 28.10.2014 Сообщений: 23 |
||||
1 |
||||
28.10.2014, 17:52. Показов 4055. Ответов 8 Метки нет (Все метки)
У меня проблема в этом коде , подскажите пожалуйста что нужно исправлять вот сам код
а вот ошибка 1>—— Сборка начата: проект: Проект3, Конфигурация: Debug Win32 ——
__________________ 0 |
Вездепух 10420 / 5692 / 1550 Регистрация: 18.10.2014 Сообщений: 14,018 |
|
28.10.2014, 17:59 |
2 |
Что такое ‘if else’??? Это бессмысленная белиберда. Очевидно имелось в виду ‘else if’… Отдельно стоит заметить, что скорее всего от вас ожидали, что вы напечатаете сами решения квадратного уравнения, а не формулы для решения из учебника. P.S. Ваша манера объединять последовательные выводы в ‘cout’ через оператор ‘&&’ остроумна, но вызывает удивление в коде у автора, который путает ‘if else’ с ‘esle if’. 0 |
5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
|
28.10.2014, 18:01 |
3 |
Что-то у вас тут не то. Во первых я вижу,что пропущена точка с запятой в 22 строке. Ну и если вы хотите,чтобы формулы записанные в cout работали,то их не нужно брать в кавычки. Добавлено через 25 секунд 0 |
0 / 0 / 0 Регистрация: 28.10.2014 Сообщений: 23 |
|
28.10.2014, 18:12 [ТС] |
4 |
спасибо за помощь но я совсем уже запутался, мне надо собрать прогу которая должен решить дискриминант , а у мя Бог знает что получился , может поможете , обясните что к чему ? 0 |
Вероника99 5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
||||
28.10.2014, 18:43 |
5 |
|||
Прогу не компилировала,но вроде ничего не упустила. Там стоит обратить внимание на то,что корень вычисляется только с неотрицательных чисел
1 |
73 / 73 / 28 Регистрация: 06.10.2013 Сообщений: 309 |
|
28.10.2014, 18:45 |
6 |
Прогу не компилировала оно и видно) для cin и cout нужна iostream, которой нет) 0 |
5 / 5 / 5 Регистрация: 16.12.2013 Сообщений: 463 |
|
28.10.2014, 18:46 |
7 |
О да,самое главное))) 0 |
BeyB 0 / 0 / 0 Регистрация: 28.10.2014 Сообщений: 23 |
||||
28.10.2014, 19:03 [ТС] |
8 |
|||
спасибо успел сделать всё кажется пол часа назад , спасибо большое за то что предупредили что мой первый код было магко говоря бесполезным
0 |
zss Модератор 12627 / 10125 / 6097 Регистрация: 18.12.2011 Сообщений: 27,158 |
||||
28.10.2014, 19:09 |
9 |
|||
Решение
1 |
- Remove From My Forums
-
Question
-
struct A { int i; A() {} A(int i) : i(i) {} }; template <typename T> struct Help { typedef A B; }; template <typename T2> int foo(T2 t2, typename Help<T2>::B b = typename Help<T2>::B(0)) { return 0; } int main() { int I; int res = foo(I); return res; } /* $ cl.exe C2059.cpp Microsoft (R) C/C++ Optimizing Compiler Version 19.15.26729 for x64 Copyright (C) Microsoft Corporation. All rights reserved. C2059.cpp C2059.cpp(22): error C2059: syntax error: '' C2059.cpp(31): fatal error C1903: unable to recover from previous error(s); stopping compilation */
- Edited by
Thursday, September 20, 2018 1:00 PM
add a line so that error message matches
- Edited by
See more:
#include "stdafx.h" #include "parser.h" #include "HashTable.h" #include "CountFrequency.h" #include <iostream> #include <string> #include <cstring> using namespace std; void parser(string line, int fileNo, class HashTable & HT, frequencyList FL[]) { char * cStr, * cPtr; string tempString; cStr = new char [line.size() + 1]; strcpy (cStr, line.c_str()); cPtr = strtok (cStr, " "); while (cPtr != NULL) { if (strcmp(cPtr, "</TEXT>") != 0 && *cPtr != '.') { tempString = string(cPtr); removeCommaBehind(tempString); removePeriodBehind(tempString); removePBehind(tempString); removePBefore(tempString); removeApsBehind(tempString); removeApBehind(tempString); removeIesBehind(tempString); removeSLBefore(tempString); removeEsBehind(tempString); removeSBehind(tempString); removeIngBehind(tempString); removeEdBehind(tempString); if(tempString.compare("a") != 0) if(tempString.compare("an") != 0) if(tempString.compare("any") != 0) if(tempString.compare("all") != 0) if(tempString.compare("and") != 0) if(tempString.compare("are") != 0) if(tempString.compare("at") != 0) if(tempString.compare("as") != 0) if(tempString.compare("b") != 0) if(tempString.compare("be") != 0) if(tempString.compare("been") != 0) if(tempString.compare("but") != 0) if(tempString.compare("by") != 0) if(tempString.compare("c") != 0) if(tempString.compare("ca") != 0) if(tempString.compare("can") != 0) if(tempString.compare("d") != 0) if(tempString.compare("e") != 0) if(tempString.compare("f") != 0) if(tempString.compare("for") != 0) if(tempString.compare("from") != 0) if(tempString.compare("g") != 0) if(tempString.compare("ga") != 0) if(tempString.compare("h") != 0) if(tempString.compare("ha") != 0) if(tempString.compare("had") != 0) if(tempString.compare("have") != 0) if(tempString.compare("he") != 0) if(tempString.compare("i") != 0) if(tempString.compare("in") != 0) if(tempString.compare("is") != 0) if(tempString.compare("it") != 0) if(tempString.compare("j") != 0) if(tempString.compare("k") != 0) if(tempString.compare("l") != 0) if(tempString.compare("like") != 0) if(tempString.compare("m") != 0) if(tempString.compare("me") != 0) if(tempString.compare("my") != 0) if(tempString.compare("n") != 0) if(tempString.compare("near") != 0) if(tempString.compare("no") != 0) if(tempString.compare("not") != 0) if(tempString.compare("o") != 0) if(tempString.compare("of") != 0) if(tempString.compare("on") != 0) if(tempString.compare("or") != 0) if(tempString.compare("out") != 0) if(tempString.compare("over") != 0) if(tempString.compare("p") != 0) if(tempString.compare("q") != 0) if(tempString.compare("r") != 0) if(tempString.compare("s") != 0) if(tempString.compare("she") != 0) if(tempString.compare("so") != 0) if(tempString.compare("t") != 0) if(tempString.compare("that") != 0) if(tempString.compare("th") != 0) if(tempString.compare("the") != 0) if(tempString.compare("them") != 0) if(tempString.compare("their") != 0) if(tempString.compare("they") != 0) if(tempString.compare("this") != 0) if(tempString.compare("to") != 0) if(tempString.compare("u") != 0) if(tempString.compare("up") != 0) if(tempString.compare("us") != 0) if(tempString.compare("v") != 0) if(tempString.compare("w") != 0) if(tempString.compare("wa") != 0) if(tempString.compare("was") != 0) if(tempString.compare("we") != 0) if(tempString.compare("were") != 0) if(tempString.compare("which") != 0) if(tempString.compare("who") != 0) if(tempString.compare("will") != 0) if(tempString.compare("with") != 0) if(tempString.compare("x") != 0) if(tempString.compare("y") != 0) if(tempString.compare("z") != 0) if(tempString.compare("") != 0) if(tempString.compare("n") != 0) if(tempString.compare(" ") != 0) if(tempString.compare(" n") != 0) if(tempString.compare("n") != 0) if(tempString.compare(",") != 0) if(tempString.compare(".") != 0) if(tempString.compare("=") != 0) { countFrequency(tempString, FL); } } cPtr = strtok(NULL, "()/ "); } delete[] cStr; } void removeCommaBehind(string &tempString) { if(tempString.find(",", tempString.length() - 2) < 35) { tempString.replace(tempString.find(",", tempString.length() - 2), tempString.length(), ""); } } void removePeriodBehind(string &tempString) { if(tempString.find(".", tempString.length() - 2) < 35) { tempString.replace(tempString.find(".", tempString.length() - 2), tempString.length(), ""); } } void removeSLBefore(string &tempString) { if(tempString[0] == '/') tempString.erase(0, 1); } void removeIesBehind(string &tempString) { if(tempString.find("ies", tempString.length() - 3) < 35) { tempString.replace(tempString.find("ies", tempString.length() - 3), tempString.length(), "y"); } } void removeEsBehind(string &tempString) { if(tempString.find("sses", tempString.length() - 4) < 35) { tempString.replace(tempString.find("sses", tempString.length() - 4), tempString.length(), "ss"); } } void removeSBehind(string &tempString) { if(tempString.find("s", tempString.length() - 1) < 35) { tempString.replace(tempString.find("s", tempString.length() - 1), tempString.length(), ""); } } void removeIngBehind(string &tempString) { if(tempString.find("ing", tempString.length() - 3) < 35) { tempString.replace(tempString.find("ing", tempString.length() - 3), tempString.length(), ""); } } void removeEdBehind(string &tempString) { if(tempString.find("ed", tempString.length() - 2) < 35) { tempString.replace(tempString.find("ed", tempString.length() - 2), tempString.length(), ""); } } void removeApsBehind(string &tempString) { if(tempString.find("'s", tempString.length() - 2) < 35) { tempString.replace(tempString.find("'s", tempString.length() - 2), tempString.length(), ""); } } void removeApBehind(string &tempString); void removeApBehind(string &tempString) { if(tempString.find("'", tempString.length() - 2) < 35) { tempString.replace(tempString.find("'", tempString.length() - 2), tempString.length(), ""); } } void removePBefore(string &tempString) { if(tempString[0] == '(') tempString.erase(0, 1); } void removePBehind(string &tempString) { if(tempString.find(")", tempString.length() - 2) < 35) { tempString.replace(tempString.find(")", tempString.length() - 2), tempString.length(), ""); } }
- Forum
- Beginners
- Namespaces & «error C2059: syntax error
Namespaces & «error C2059: syntax error : ‘string’»
REPOSTED THE PROBLEM BELOW WITH ALL SUGGESTED IMPROVEMENTS. STILL PROBLEMS THOUGH!
THANKS GUYS
Last edited on
|
|
Remove the comma after LOG_ALL
LOG_ALL,
Thanks xandel33, but that hasn’t cleared up the problem. I changed my enum to
|
|
But theres still the same error appearing on compile
Can you post the entire compile error?
Just as a matter of good programming practice, never use a namespace in a header file. You should remove the
from your header file and prefix everything that needs to be with std::.
OK, I’ve tried to tidy this up to make it a bit clearer. I’ve implemented the suggestions above, but still no luck. The error is caused by the member definition:
utilities::CLogFile m_Log(«global_log»,LOG_ALL,1);
//returns — error C2059: syntax error : ‘string’
Heres the header with the compiler error:
|
|
And heres a reduced class with zero functionality (but still the error)
|
|
Is there a problem with my member defn?
Last edited on
You can’t initialize m_Log like that. You need to initialize it in the constructor:
|
|
I hope this helps! ^_^
rpgfan
Last edited on
Ahhhh ….. Initialization Lists(?) Never really used or paid any real attention to them in examples! Time to read up on them i think!
Thanks rpgfan and everyone else who offered advice. It’s appreciated!
Doug
Yep, initialization lists. Just beware of them when you play with virtual inheritance. They come back to bite you.
Topic archived. No new replies allowed.