Error c2143 синтаксическая ошибка отсутствие перед using namespace

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 s...

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.

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

Hi Everyone,

I getting that error when I try to build my work. The program is simple Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner book’s example program » Speed Typing Game»

I just downloaded Visual C++ Exprees Edition 2008 and I dont know what sould I do to stop receiving that  error

Appreciate  helps and suggestions;

Thanks

SZ

————————————————————————————————————————————————————————

#pragma once


namespace My1 {

 using namespace System;
 using namespace System::ComponentModel;
 using namespace System::Collections;
 using namespace System::Windows::Forms;
 using namespace System:Big Smileata;
 using namespace System:Big Smilerawing;
 };

 /// <summary>
 /// Summary for Form1
 ///
 /// WARNING: If you change the name of this class, you will need to change the
 ///          ‘Resource File Name’ property for the managed resource compiler tool
 ///          associated with all .resx files this class depends on.  Otherwise,
 ///          the designers will not be able to interact properly with localized
 ///          resources associated with this form.
 /// </summary>

 public ref class Form1 : public System::Windows::Forms::Form
 {
 public:
  Form1(void)
  {
   InitializeComponent();
   //
   //TODO: Add the constructor code here
   //
  }

 protected:
  /// <summary>
  /// Clean up any resources being used.
  /// </summary>
  ~Form1()
  {
   if (components)
   {
    delete components;
   }
  }
 private: System::Windows::Forms::TextBox^  textBox1;
 private: System::Windows::Forms::TextBox^  textBox2;
 private: System::Windows::Forms::Button^  button1;
 private: System::Windows::Forms::Button^  button2;
 private: System::Windows::Forms::Button^  button3;
 private: System::Windows::Forms::TextBox^  textBox3;
 private: System::Windows::Forms::Timer^  timer1;
 private: System::Windows::Forms::Button^  button4;
 private: System::ComponentModel::IContainer^  components;
 protected:

 private:
  /// <summary>
  /// Required designer variable.
  /// </summary>
  int intLevel; 
  int intTimer;
  int intHata;
  

#pragma region Windows Form Designer generated code
  /// <summary>
  /// Required method for Designer support — do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  void InitializeComponent(void)
  {
   this->components = (gcnew System::ComponentModel::Container());
   this->textBox1 = (gcnew System::Windows::Forms::TextBox());
   this->textBox2 = (gcnew System::Windows::Forms::TextBox());
   this->button1 = (gcnew System::Windows::Forms::Button());
   this->button2 = (gcnew System::Windows::Forms::Button());
   this->button3 = (gcnew System::Windows::Forms::Button());
   this->textBox3 = (gcnew System::Windows::Forms::TextBox());
   this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));
   this->button4 = (gcnew System::Windows::Forms::Button());
   this->SuspendLayout();
   //
   // textBox1
   //
   this->textBox1->BackColor = System:Big Smilerawing:Tongue TiedystemColors::InactiveCaptionText;
   this->textBox1->Font = (gcnew System:Big Smilerawing::Font(L»Microsoft Sans Serif», 14, System:Big Smilerawing::FontStyle::Bold, System:Big Smilerawing::GraphicsUnit:Stick out tongueoint,
    static_cast<System::Byte>(162)));
   this->textBox1->Location = System:Big Smilerawing:Stick out tongueoint(23, 33);
   this->textBox1->Name = L»textBox1″;
   this->textBox1->ReadOnly = true;
   this->textBox1->Size = System:Big Smilerawing:Tongue Tiedize(625, 29);
   this->textBox1->TabIndex = 0;
   this->textBox1->Text = L»Click Start To Begin !»;
   this->textBox1->TextAlign = System::Windows::Forms::HorizontalAlignment::Center;
   //
   // textBox2
   //
   this->textBox2->BackColor = System:Big Smilerawing:Tongue TiedystemColors::ButtonFace;
   this->textBox2->Font = (gcnew System:Big Smilerawing::Font(L»Microsoft Sans Serif», 14, System:Big Smilerawing::FontStyle::Bold, System:Big Smilerawing::GraphicsUnit:Stick out tongueoint,
    static_cast<System::Byte>(162)));
   this->textBox2->Location = System:Big Smilerawing:Stick out tongueoint(27, 116);
   this->textBox2->Name = L»textBox2″;
   this->textBox2->Size = System:Big Smilerawing:Tongue Tiedize(620, 29);
   this->textBox2->TabIndex = 1;
   this->textBox2->Text = L»Type Here»;
   this->textBox2->TextAlign = System::Windows::Forms::HorizontalAlignment::Center;
   //
   // button1
   //
   this->button1->Font = (gcnew System:Big Smilerawing::Font(L»Microsoft Sans Serif», 18, System:Big Smilerawing::FontStyle::Bold, System:Big Smilerawing::GraphicsUnit:Stick out tongueoint,
    static_cast<System::Byte>(162)));
   this->button1->ForeColor = System:Big Smilerawing::Color::Red;
   this->button1->Location = System:Big Smilerawing:Stick out tongueoint(48, 182);
   this->button1->Name = L»button1″;
   this->button1->Size = System:Big Smilerawing:Tongue Tiedize(110, 56);
   this->button1->TabIndex = 2;
   this->button1->Text = L»Start!!»;
   this->button1->UseVisualStyleBackColor = true;
   this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
   //
   // button2
   //
   this->button2->Font = (gcnew System:Big Smilerawing::Font(L»Microsoft Sans Serif», 18, System:Big Smilerawing::FontStyle::Bold, System:Big Smilerawing::GraphicsUnit:Stick out tongueoint,
    static_cast<System::Byte>(162)));
   this->button2->Location = System:Big Smilerawing:Stick out tongueoint(228, 184);
   this->button2->Name = L»button2″;
   this->button2->Size = System:Big Smilerawing:Tongue Tiedize(110, 56);
   this->button2->TabIndex = 3;
   this->button2->Text = L»Done»;
   this->button2->UseVisualStyleBackColor = true;
   this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
   //
   // button3
   //
   this->button3->Font = (gcnew System:Big Smilerawing::Font(L»Microsoft Sans Serif», 18, System:Big Smilerawing::FontStyle::Bold, System:Big Smilerawing::GraphicsUnit:Stick out tongueoint,
    static_cast<System::Byte>(162)));
   this->button3->Location = System:Big Smilerawing:Stick out tongueoint(144, 267);
   this->button3->Name = L»button3″;
   this->button3->Size = System:Big Smilerawing:Tongue Tiedize(110, 56);
   this->button3->TabIndex = 4;
   this->button3->Text = L»Quit»;
   this->button3->UseVisualStyleBackColor = true;
   //
   // textBox3
   //
   this->textBox3->BackColor = System:Big Smilerawing:Tongue TiedystemColors::MenuHighlight;
   this->textBox3->Font = (gcnew System:Big Smilerawing::Font(L»Arial», 72, System:Big Smilerawing::FontStyle::Bold, System:Big Smilerawing::GraphicsUnit:Stick out tongueoint,
    static_cast<System::Byte>(162)));
   this->textBox3->ForeColor = System:Big Smilerawing::Color::Crimson;
   this->textBox3->Location = System:Big Smilerawing:Stick out tongueoint(450, 178);
   this->textBox3->Name = L»textBox3″;
   this->textBox3->Size = System:Big Smilerawing:Tongue Tiedize(137, 118);
   this->textBox3->TabIndex = 5;
   this->textBox3->TextAlign = System::Windows::Forms::HorizontalAlignment::Center;
   //
   // timer1
   //
   this->timer1->Interval = 1000;
   this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick);
   //
   // button4
   //
   this->button4->BackColor = System:Big Smilerawing:Tongue TiedystemColors::ButtonFace;
   this->button4->Font = (gcnew System:Big Smilerawing::Font(L»Microsoft Sans Serif», 8.25F, System:Big Smilerawing::FontStyle::Bold, System:Big Smilerawing::GraphicsUnit:Stick out tongueoint,
    static_cast<System::Byte>(162)));
   this->button4->ForeColor = System:Big Smilerawing::Color:Big SmilearkSlateGray;
   this->button4->Location = System:Big Smilerawing:Stick out tongueoint(640, 5);
   this->button4->Name = L»button4″;
   this->button4->Size = System:Big Smilerawing:Tongue Tiedize(26, 22);
   this->button4->TabIndex = 6;
   this->button4->Text = L»C»;
   this->button4->UseVisualStyleBackColor = false;
   //
   // Form1
   //
   this->AutoScaleDimensions = System:Big Smilerawing:Tongue TiedizeF(6, 13);
   this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
   this->BackColor = System:Big Smilerawing:Tongue TiedystemColors::ButtonHighlight;
   this->ClientSize = System:Big Smilerawing:Tongue Tiedize(678, 329);
   this->Controls->Add(this->button4);
   this->Controls->Add(this->textBox3);
   this->Controls->Add(this->button3);
   this->Controls->Add(this->button2);
   this->Controls->Add(this->button1);
   this->Controls->Add(this->textBox2);
   this->Controls->Add(this->textBox1);
   this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::Fixed3D;
   this->Name = L»Form1″;
   this->Text = L»Typing Game»;
   this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
   this->ResumeLayout(false);
   this->PerformLayout();

  }
#pragma endregion
 private: System::Void Form1_Load(System:Surprisebject^  sender, System::EventArgs^  e) {

          intTimer=intHata=intLevel=0;
    }
private: System::Void button1_Click(System:Surprisebject^  sender, System::EventArgs^  e) {

     intLevel++;
    button1->Font = (gcnew System:Big Smilerawing::Font(L»Microsoft Sans Serif», 18, System:Big Smilerawing::FontStyle::Bold, System:Big Smilerawing::GraphicsUnit:Stick out tongueoint,
    static_cast<System::Byte>(162)));
    button1->Text = (String::Concat («Level», intLevel.ToString(),»!!»));
    button1->Enabled = false;
    switch(intLevel) {

     case 1:
      textBox1->Text = «Adamın biri bir gün yolda giderken ;»;
      break;
     case 2:
      textBox1->Text = «Dünyaca ünlü ateşle ve unut güdümlü füze. Türk Deniz Kuvvetlerde kullanılıyor»;
      break;
     case 3:
      textBox1->Text = «Proje ile, seramik matrisli kompozit (CMC) malzemeler sınıfına giren silisyum-karbür»;
      break;
     default:
      textBox1->Text = «Click Start To Begin !»;
      break;
    };
    textBox2->Text = «»;
    textBox2->Focus();
    timer1->Enabled = true;
   }
private: System::Void timer1_Tick(System:Surprisebject^  sender, System::EventArgs^  e) {
    intTimer++;
    textBox3->Text =(31-intTimer).ToString();
    if(intTimer == 30){
     timer1->Enabled = false;
     textBox3->Text = «»;
     button1->Enabled =false;
     button2->Enabled =false;
    if (String::IsNullOrEmpty (textBox2->Text))
    {
     MessageBox:Tongue Tiedhow(«Yazı Yazilmamis»,»hata»,MessageBoxButtons:SurpriseK,MessageBoxIcon::Error);
        return;
    };
    if(String::Compare (textBox2->Text , textBox1->Text )== 0){
     textBox2->Enabled = false;
     intLevel++;
     intTimer=0;
     MessageBox:Tongue Tiedhow(String::Concat («Dogru Cevap»,intLevel.ToString(),»Seviyesine Geçtiniz»),»Tebrikler»,MessageBoxButtons:SurpriseK,MessageBoxIcon::Asterisk );

    }
    else {
     textBox2->Enabled = false;
     intTimer=0;
     intHata++;
     MessageBox:Tongue Tiedhow(String::Concat («Yanlış Cevap n»,intHata.ToString(),»Hataya Ulaştınız»),»Yanlış»,MessageBoxButtons:SurpriseK,MessageBoxIcon::Error);
   };
};
    button1->Enabled = true;
    button2->Enabled = true;
    button1->Focus();
   }

   private: System::Void button2_Click(System:Surprisebject^  sender, System::EventArgs^  e) {
    textBox3->Text = «»;
    timer1->Enabled = false;
    button2->Enabled = false;
    if(String::Compare (textBox2->Text , textBox1->Text )== 0){
     textBox2->Enabled = false;
     intLevel++;
     intTimer=0;
     MessageBox:Tongue Tiedhow(String::Concat («Dogru Cevap»,intLevel.ToString(),»Seviyesine Geçtiniz»),»Tebrikler»,MessageBoxButtons:SurpriseK,MessageBoxIcon::Information);

    }
    else {
     textBox2->Enabled = false;
     intHata++;
     MessageBox:Tongue Tiedhow(String::Concat («Yanlış Cevap n»,intHata.ToString(),»Hataya Ulaştınız»),»Yanlış»,MessageBoxButtons:SurpriseK,MessageBoxIcon::Error);
   };
   button1->Enabled = true;
   button2->Enabled = true;
   button1->Focus();

   
   }

————————————————————————————————————————————————————————-

Oleg Pridarun

2 / 2 / 1

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

Сообщений: 91

1

02.07.2017, 13:05. Показов 6682. Ответов 12

Метки using namespace, visual studio, с, Синтаксис (Все метки)


У меня есть заголовочный файл LanguageEng.h В нём находится код:

C++
1
2
3
4
5
6
#pragma once
#include <iostream>
 
using namespace std;
 
string StartGameTextEng = "To start the game, enter <<Start>>/nTo open the settings, enter <<Settings>>/nTo exit, enter <<Exit>>";

При компиляции программы с этим заголовочным файлом происходит ошибка: c:users***onedriveпрограммыgamelanguageeng.h (4): error C2143: синтаксическая ошибка: отсутствие «;» перед «using namespace»
Я пробовал поставить поставить после #include <iostream> ;, но ошибка осталась.
В чём проблема?

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



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

Попробуйте добавить #include <string>



0



2 / 2 / 1

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

Сообщений: 91

02.07.2017, 14:14

 [ТС]

4

Цитата
Сообщение от Новичок
Посмотреть сообщение

Код программы в студию.

Давайте я лучше весь проект кину, так как он многофайловый

Добавлено через 5 минут

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

Попробуйте добавить #include <string>

Проблема осталась та же. Ни каких изменений



0



3433 / 2812 / 1249

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

Сообщений: 9,426

02.07.2017, 16:40

5

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

Давайте я лучше весь проект кину

И где же он?



0



2 / 2 / 1

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

Сообщений: 91

02.07.2017, 17:21

 [ТС]

6

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

И где же он?

Хотел поместить его на гугл диск, но это, похоже заняло бы несколько часов (не знаю по какой причине). Скинуть код из файла с int main()?



0



3433 / 2812 / 1249

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

Сообщений: 9,426

02.07.2017, 17:24

7

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

Хотел поместить его на гугл диск, но это, похоже заняло бы несколько часов (не знаю по какой причине).

Здесь, в архиве, выложи. Или очень большой?

Добавлено через 59 секунд

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

Скинуть код из файла с int main()?

Хедеры, с определениями классов, есть в проекте?



0



2 / 2 / 1

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

Сообщений: 91

02.07.2017, 20:42

 [ТС]

8

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

Здесь, в архиве, выложи. Или очень большой?

Добавлено через 59 секунд

Хедеры, с определениями классов, есть в проекте?

Классы не использовал. Я в них пока не разобрался. На данный момент только функции и переменные в хедерах



0



3433 / 2812 / 1249

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

Сообщений: 9,426

02.07.2017, 20:56

9

Выкладывать проект будешь, или можно отписываться от темы?



0



5225 / 3197 / 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

так в этом файле и исправляй ошибку по пути
c:users***onedriveпрограммыgamelanguageeng.h

так как LanguageEng.h и такой languageeng.h это разные файлы или нет?



0



2 / 2 / 1

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

Сообщений: 91

05.07.2017, 22:50

 [ТС]

12

Простите, мне отключили интернет. Проблему решил. languageeng и LanguageEng для Visual у меня одно и тоже. Проблема была в другом хедере. В нём была пропущена ;, и другие хедеры на это реагировали



0



dawn artist

Заблокирован

05.07.2017, 23:01

13

Лучший ответ Сообщение было отмечено Oleg Pridarun как решение

Решение

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

Проблема была в другом хедере.

Это было сразу очевидно.



1



Содержание

  1. Ошибка компилятора C2143
  2. Compiler Error C2143
  3. Error c2143 syntax error missing before что это
  4. Answered by:
  5. Question
  6. Answers
  7. All replies
  8. Error c2143 syntax error missing before что это
  9. Asked by:
  10. Question
  11. All replies

Ошибка компилятора C2143

синтаксическая ошибка: отсутствует «token1» перед «token2»

Компилятор ожидал определенный маркер (т. е. элемент языка, отличный от пробела) и нашел вместо него другой маркер.

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

C2143 может возникать в разных ситуациях.

Это может произойти, когда за оператором, который может квалифицировать имя ( :: , -> и . ), должно следовать ключевое слово template , как показано в следующем примере:

По умолчанию В C++ предполагается, что Ty::PutFuncType это не шаблон, поэтому следующее интерпретируется как знак меньшего. Необходимо явно сообщить компилятору, что PutFuncType является шаблоном, чтобы он смог правильно проанализировать угловую скобку. Чтобы исправить эту ошибку, используйте ключевое template слово для имени зависимого типа, как показано ниже:

C2143 может возникать, если используется /clr и using директива имеет синтаксическую ошибку:

Это также может произойти при попытке скомпилировать файл исходного кода с помощью синтаксиса CLR без использования /clr:

Первый символ без пробелов, следующий за оператором if , должен быть левой скобкой. Компилятор не может перевести ничего другого:

C2143 может возникать, когда закрывающая фигурная скобка, круглые скобки или точка с запятой отсутствуют в строке, в которой обнаружена ошибка, или в одной из строк выше:

Или при наличии недопустимого тега в объявлении класса:

Или, если метка не присоединена к оператору. Если необходимо поместить метку сама по себе, например в конце составного оператора, прикрепите ее к оператору NULL:

Эта ошибка может возникать, когда выполняется неквалифицированный вызов типа в стандартной библиотеке C++:

Или отсутствует ключевое typename слово:

Или при попытке определить явное создание экземпляра:

В программе C переменные должны быть объявлены в начале функции и не могут быть объявлены после того, как функция выполнит инструкции, не являющиеся объявлениями.

Источник

Compiler Error C2143

syntax error : missing ‘token1’ before ‘token2’

The compiler expected a specific token (that is, a language element other than white space) and found another token instead.

Check the C++ Language Reference to determine where code is syntactically incorrect. Because the compiler may report this error after it encounters the line that causes the problem, check several lines of code that precede the error.

C2143 can occur in different situations.

It can occur when an operator that can qualify a name ( :: , -> , and . ) must be followed by the keyword template , as in this example:

By default, C++ assumes that Ty::PutFuncType isn’t a template; therefore, the following is interpreted as a less-than sign. You must tell the compiler explicitly that PutFuncType is a template so that it can correctly parse the angle bracket. To correct this error, use the template keyword on the dependent type’s name, as shown here:

C2143 can occur when /clr is used and a using directive has a syntax error:

It can also occur when you are trying to compile a source code file by using CLR syntax without also using /clr:

The first non-whitespace character that follows an if statement must be a left parenthesis. The compiler cannot translate anything else:

C2143 can occur when a closing brace, parenthesis, or semicolon is missing on the line where the error is detected or on one of the lines just above:

Or when there’s an invalid tag in a class declaration:

Or when a label is not attached to a statement. If you must place a label by itself, for example, at the end of a compound statement, attach it to a null statement:

The error can occur when an unqualified call is made to a type in the C++ Standard Library:

Or there is a missing typename keyword:

Or if you try to define an explicit instantiation:

In a C program, variables must be declared at the beginning of the function, and they cannot be declared after the function executes non-declaration instructions.

Источник

Error c2143 syntax error missing before что это

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

#ifndef DEPT_INCLUDED
#define DEPT_INCLUDED

typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;

Error message is: «Error 1 error C2143: syntax error : missing ‘;’ before ‘ ‘» and it is point to «typedef struct <» line.

Can somebody help? Thanks.

Answers

typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;

it’s:
typedef unsigned long int UL;

You should include this typedef before the structure definition!

#ifndef DEPT_INCLUDED
#define DEPT_INCLUDED

typedef unsigned long UL;

typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;

#endif
Microsoft MVP — Visual C++
Blog: http://nibuthomas.com Posts are provided as is without warranties or guaranties.

What happens if you temporary put the expected ‘;’ before typedef? What is the first error displayed?

typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;

If you’re using C++ why can’t you just do this:

There are 10 types of people in this world; those who understand binary and those who don’t.

I tried using the that code above but still.

‘CompileAs’ propertry for this project has been set to C++.

#ifndef DEPT_INCLUDED
#define DEPT_INCLUDED

typedef struct <
UL online;
UL positive_standalone;
UL negative_standalone;
UL sales;
> GROSS_TOTALS;
#endif

Источник

Error c2143 syntax error missing before что это

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

Ok.. so I decide to start learning some inteligence 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

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?

Go to the directory indicated in the error message:

c:program filesmicrosoft visual studio 9.0vcinclude

Open the file istream with an editor or viewer. (Notepad will do.)

Copy and paste the first 20 lines of that file into a post here.

I suspect that you have a missing semi-colon or closing brace in your stdafx.h header file. You should begin your search there.

Best Wishes,
-David Delaune

Quote>I suspect that you have a missing semi-colon or closing brace in your stdafx.h header file

Note that the OP said:

Quote>after typing the attached code I am unable to build all previous project lessons

I take this to mean that projects which previously built cleanly will no longer do so.
Since each project should have it’s own stdafx.h it seems unlikely that this is the
source of the problem.

Note that the error message says:

missing ‘;’ before ‘namespace’

and points to line 13 of the header istream.

I see no word «namespace» anywhere in the istream header of my installation.

Note that the error message says:

missing ‘;’ before ‘namespace’

and points to line 13 of the header istream.

I see no word «namespace» anywhere in the istream header of my installation.

Check your definition of _STD_BEGIN.

Best Wishes,
-David Delaune

Quote>Check your definition of _STD_BEGIN.

Will no-one rid me of these meddlesome macros?

Good catch. Thanks.

That is correct regarding all the previous compiled projects, I have attached the requested code

That looks kosher, so the problem is probably earlier.

Looking at the include chain from iostream, it pulls in istream which pulls in ostream
which pulls in ios which pulls in xlocnum which pulls in climits, etc. etc. Before that,
stdafx.h pulls in targetver.h etc. etc. All of the above are pulled in (at least a few
dozen files) before we reach line 13 of istream where the error occurs.

First, go to the Project Properties and under
Configuration Properties=>C/C++=>Advanced
set the field «Show Includes» to «Yes» then click on «Apply/OK».

Go to the output window, select all of the lines, copy to Windows clipboard
and paste here in a message.

Second, answer these questions:

(1) Did you give each project its own name, or did you use the same name for each
project?

(2) Click on the Build menu, then click on «Clean Solution». Rebuild. Does the
problem persist?

(3) If the problem is still there, go to the Project Properties and under
Configuration Properties=>C/C++=>Precompiled Headers
set «Create/Use Precompiled Header» to «Not Using Precompiled Headers»
then click on «Apply/OK». Rebuild. Does the problem persist?

Источник

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    Компилятор не в себе
    , глючит.. выдаёт ошибку там, где её быть не должно

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    15.01.10, 13:44

      после попытки компиляции программы в MVisual C++ 2008 Express пишет следующие тупые ошибки:

      Ошибка 1 error C2143: синтаксическая ошибка: отсутствие «;» перед «using»
      что-то я не помню, чтобы перед using namespace std; писался ;

      Ошибка 2 error C2628: недопустимый ‘Temperature’ с последующим ‘void’ (возможно, отсутствует ‘;’)
      Ошибка 3 error C2556: Temperature Temperature::set(std::string): перегруженная функция отличается от ‘void Temperature::set(std::string)’ только возвращаемым типом
      Ошибка 3 error C2371: Temperature::set: переопределение; различные базовые типы
      тут я тоже не пойму в чём у меня могла быть ошибка. вот код:

      ExpandedWrap disabled

         //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();

        }

      ExpandedWrap disabled

        //gradus.cpp

        #include «gradus.h»

        void Temperature::set(string str)

        {…}

        int Temperature::change()

        {…}

        void Temperature::show()

        {…}


      kanes



      Сообщ.
      #2

      ,
      15.01.10, 13:45

        При определении класса после } ставят ;


        Potroshitell



        Сообщ.
        #3

        ,
        15.01.10, 13:46

          аа.. сори, не компилятор глючит, а я! вопрос в топку :lol:

          Сообщение отредактировано: Potroshitell — 15.01.10, 13:46


          kanes



          Сообщ.
          #4

          ,
          15.01.10, 13:48

            Цитата Potroshitell @ 15.01.10, 13:45

            ааа, или возможно просто set — ключевое слово.

            не ключевое, но слово обозначающее контейнер из STL std::set, правда для него требуется заголовок <set> так что дело не в этом


            Potroshitell



            Сообщ.
            #5

            ,
            15.01.10, 14:07

              я ещё вот хотел бы задать 1 мини-вопросик.. ради него наверно не стоит создавать отдельную тему=)

              ExpandedWrap disabled

                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



              Сообщ.
              #6

              ,
              15.01.10, 14:31

                Junior

                *

                Рейтинг (т): 3

                Цитата Potroshitell @ 15.01.10, 14:07

                если функция определяется в классе как встроенная, то нужно ставить ; после } ?

                не нужно.


                Potroshitell



                Сообщ.
                #7

                ,
                15.01.10, 14:32


                  Mr.Delphist



                  Сообщ.
                  #8

                  ,
                  17.01.10, 14:44

                    И это… того… Не пиши «using namespace» в заголовочных файлах, а то это очень «добрый» сюрприз себе на будущее :)
                    Ибо этот юзинг прилетит во все те файлы, куда ты будешь включать свой gradus.h (или любой заголовочник, явно/неявно включающий gradus.h). Очень «весело» ловить ошибки в стиле «код перестал компилиться после добавки одного #include, а ведь больше ничего не менял» или «компилятор не видит метод моего класса»

                    0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                    0 пользователей:

                    • Предыдущая тема
                    • C/C++: Общие вопросы
                    • Следующая тема

                    Рейтинг@Mail.ru

                    [ Script execution time: 0,0415 ]   [ 16 queries used ]   [ Generated: 9.02.23, 12:12 GMT ]  

                    Наследую класс Typeinfo от TypeSize.

                    TypeSize.h

                    using namespace std;
                    
                    template <class T1>
                    class TypeSize
                    {
                    public:
                    	TypeSize(T1 value);
                    
                    	void DataTypeSize();
                    
                    protected:
                    	T1 value;
                    };

                    TypeInfo.h

                    using namespace std;
                    
                    template <class T1>
                    class TypeInfo : public TypeSize<T1> // Здесь получаю C2143 синтаксическая ошибка: отсутствие "," перед "<"
                    {
                    public:
                    	TypeInfo(T1 value);
                    	
                    	void ShowTypeName();
                    };

                    stdafx.h

                    #pragma once
                    
                    #include "targetver.h"
                    #include <tchar.h>
                    #include <iostream>
                    
                    #include "TypeInfo.h"
                    #include "TypeSize.h"

                    Подскажите, в чем может быть причина?


                    • Вопрос задан

                      более трёх лет назад

                    • 102 просмотра

                    Не знаю зачем вам это нужно, не разобравшись с синтаксисом и прочими базовыми вещами лезть в шаблоны. У Вас там все сплошная ошибка.

                    SizeType.h

                    #pragma once
                    #include <iostream>
                    
                    template<typename T>
                    class TypeSize
                    {
                    public:
                      TypeSize(T v) : value{ v } {};
                      ~TypeSize() {};
                      void dataTypeSize();
                    protected:
                      T value;
                    };
                    
                    template<typename T>
                    void TypeSize<T>::dataTypeSize()
                    {
                      std::cout << "size: " << sizeof(value) << std::endl;
                    }

                    TypeInfo.h

                    #pragma once
                    #include <typeinfo> // std::typeid()
                    #include "TypeSize.h"
                    
                    template<typename T>
                    class TypeInfo : public TypeSize<T>
                    {
                    public:
                      TypeInfo(T v) : TypeSize<T>(v) {};
                      ~TypeInfo() {};
                      void showTypeInfo();
                    };
                    
                    template<typename T>
                    void TypeInfo<T>::showTypeInfo()
                    {
                      std::cout << "type: " << typeid(this->value).name() << std::endl;
                    }

                    main.cpp

                    #include "TypeInfo.h"
                    
                    int main()
                    {
                      int a{ 5 };
                      TypeInfo<int> infInt(a);
                      infInt.dataTypeSize();
                      infInt.showTypeInfo();
                      std::getchar();
                    }

                    Пригласить эксперта


                    • Показать ещё
                      Загружается…

                    09 февр. 2023, в 15:06

                    2000 руб./за проект

                    09 февр. 2023, в 15:02

                    12000 руб./за проект

                    09 февр. 2023, в 14:22

                    1500 руб./за проект

                    Минуточку внимания

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

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

                  • Error c2143 syntax error missing before type
                  • Error c2143 syntax error missing before constant
                  • Error c2131 выражение не определяется константой
                  • Error c2131 expression did not evaluate to a constant
                  • Error c2110 невозможно добавить два указателя

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

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