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

Oleg Pridarun

2 / 2 / 1

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

Сообщений: 91

1

02.07.2017, 13:05. Показов 7261. Ответов 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\программы\game\languageeng.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



3434 / 2813 / 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



3434 / 2813 / 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



3434 / 2813 / 1249

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

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

02.07.2017, 20:56

9

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



0



5231 / 3203 / 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

так в этом файле и исправляй ошибку по пути
c:\users\***\onedrive\программы\game\languageeng.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



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.

    msm.ru

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

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

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

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



    Сообщ.
    #1

    ,

      после попытки компиляции программы в 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

      ,

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


        Potroshitell



        Сообщ.
        #3

        ,

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

          Сообщение отредактировано: Potroshitell


          kanes



          Сообщ.
          #4

          ,

            Цитата Potroshitell @

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

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


            Potroshitell



            Сообщ.
            #5

            ,

              я ещё вот хотел бы задать 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


              zim22



              Сообщ.
              #6

              ,

                Junior

                *

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

                Цитата Potroshitell @

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

                не нужно.


                Potroshitell



                Сообщ.
                #7

                ,


                  Mr.Delphist



                  Сообщ.
                  #8

                  ,

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

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

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

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

                    Рейтинг@Mail.ru

                    [ Script execution time: 0,0830 ]   [ 16 queries used ]   [ Generated: 23.09.23, 02:18 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++
                    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

                    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

                    так в этом файле и исправляй ошибку по пути
                    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

                    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?

                      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,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

                                      Wallter's user avatar

                                      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-Eric's user avatar

                                      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

                                      sth's user avatar

                                      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

                                      Метки нет (Все метки)


                                      У меня проблема в этом коде , подскажите пожалуйста что нужно исправлять

                                      вот сам код

                                      C++
                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      9
                                      10
                                      11
                                      12
                                      13
                                      14
                                      15
                                      16
                                      17
                                      18
                                      19
                                      20
                                      21
                                      22
                                      23
                                      24
                                      25
                                      26
                                      27
                                      28
                                      29
                                      30
                                      31
                                      32
                                      33
                                      34
                                      35
                                      
                                      #include <iostream>
                                      #include <cmath>
                                      #include <conio.h>
                                       
                                      using namespace std;
                                      int main()
                                       
                                      {
                                          //Declare Variables
                                          double x, x1, x2, a, b, c;
                                       
                                          cout << "Input values of a, b, and c.";
                                          cin >> a >> b >> c;
                                       
                                          for (int i = 1; i <= 10; ++i);
                                          {
                                              if ((b * b - 4 * a * c) > 0)
                                                  cout << "x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)" &&
                                                  cout << "x2 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)";
                                       
                                              if else ((b * b - 4 * a * c) = 0)
                                                  cout << "x = ((-b + sqrt(b * b - 4 * a * c)) / (2 * a)"
                                       
                                                  if else ((b * b - 4 * a * c) < 0)
                                                      cout << "x1 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a)" &&
                                                      cout << "x2 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a)";
                                       
                                              _getch();
                                       
                                          }
                                       
                                       
                                          return (0);
                                       
                                      }

                                      а вот ошибка

                                      1>—— Сборка начата: проект: Проект3, Конфигурация: Debug Win32 ——
                                      1> Исходный код.cpp
                                      1>c:userspc hackerdocumentsvisual studio 2013projectsпроект3проект3исходный код.cpp(21): error C2059: синтаксическая ошибка: else
                                      ========== Сборка: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

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

                                      0

                                      Вездепух

                                      Эксперт CЭксперт С++

                                      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 секунд
                                      И надо писать else if

                                      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

                                      Прогу не компилировала,но вроде ничего не упустила. Там стоит обратить внимание на то,что корень вычисляется только с неотрицательных чисел

                                      C++
                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      9
                                      10
                                      11
                                      12
                                      13
                                      14
                                      15
                                      16
                                      17
                                      18
                                      19
                                      20
                                      21
                                      22
                                      23
                                      24
                                      25
                                      26
                                      27
                                      28
                                      29
                                      30
                                      31
                                      32
                                      33
                                      34
                                      
                                      #include <cmath>
                                      #include <conio.h>
                                       
                                      using namespace std;
                                      int main()
                                       
                                      {
                                          //Declare Variables
                                          double x=0, x1=0, x2=0, a, b, c;
                                       
                                          cout << "Input values of a, b, and c.";
                                          cin >> a >> b >> c;
                                       
                                          
                                              if ((b * b - 4 * a * c) > 0)
                                            {      x1=x2=(-b + sqrt((float)(b * b - 4 * a * c))) / (2 * a);
                                            cout<<" "<<x1<<x2<<endl;
                                       
                                              }
                                       
                                           else if((b * b - 4 * a * c) == 0)
                                       {            x=(-b + sqrt(abs((b * b - 4.0 * a * c)))) / (2 * a);
                                               cout<<" "<<x<<endl;
                                              }
                                               else if ((b * b - 4 * a * c) < 0)
                                                  {   x1=x2=(-b + sqrt(abs((float)(b * b - 4 * a * c)))) * sqrt (abs((-1.0) / (2 * a)));
                                            cout<<" "<<x1<<endl;
                                          
                                           }
                                          
                                       
                                          return (0);
                                       
                                      }

                                      1

                                      73 / 73 / 28

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

                                      Сообщений: 309

                                      28.10.2014, 18:45

                                      6

                                      Цитата
                                      Сообщение от Вероника99
                                      Посмотреть сообщение

                                      Прогу не компилировала

                                      оно и видно) для 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

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

                                      C++
                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      9
                                      10
                                      11
                                      12
                                      13
                                      14
                                      15
                                      16
                                      
                                      #include <iostream>
                                      #include <conio.h>
                                      using namespace std;
                                      int main()
                                      {
                                          int x, y, s;
                                          cin >> x;
                                          cin >> y;
                                          s = x + y;
                                              cout << s;
                                              
                                              _getch();
                                       
                                              return 0;
                                       
                                      }

                                      0

                                      zss

                                      Модератор

                                      Эксперт С++

                                      12627 / 10125 / 6097

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

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

                                      28.10.2014, 19:09

                                      9

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

                                      Решение

                                      C++
                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      9
                                      10
                                      11
                                      12
                                      13
                                      14
                                      15
                                      16
                                      17
                                      18
                                      19
                                      20
                                      21
                                      22
                                      23
                                      24
                                      25
                                      26
                                      27
                                      28
                                      29
                                      30
                                      31
                                      32
                                      33
                                      34
                                      
                                      #include <cmath>
                                      #include <iostream>
                                      using namespace std;
                                      int main()
                                      {
                                          cout << "Input values of a, b, and c.";
                                          double a, b, c;
                                          cin >> a >> b >> c;
                                           if(a==0)
                                          {
                                               if(b!=0)
                                               {
                                                      double x=-c/b;
                                                      cout<<" "<<x<<endl;
                                               }else
                                                      cout<<" No solutionn";
                                              return 0;
                                          }
                                       
                                          double D=b * b - 4 * a * c;
                                          if (D>0)
                                          {     
                                               double x1=(-b + sqrt(D)) / (2. * a);
                                               double x2=(-b - sqrt(D)) / (2. * a);
                                               cout<<" "<<x1<<" "<<x2<<endl;
                                          }else 
                                          if(D == 0)
                                          {            
                                                x= -b / (2 * a);
                                                cout<<" "<<x<<endl;
                                          }else
                                                cout<<" No solutionn";
                                          return 0;    
                                      }

                                      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

                                      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

                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      enum eLogEntryType { LOG_GENERAL = 0, LOG_WARNING, LOG_DEBUG, LOG_ALL, }; 

                                      Remove the comma after LOG_ALL

                                      LOG_ALL,

                                      Thanks xandel33, but that hasn’t cleared up the problem. I changed my enum to

                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      enum eLogEntryType { LOG_GENERAL = 0, LOG_WARNING, LOG_DEBUG, LOG_ALL };

                                      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:

                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      9
                                      10
                                      11
                                      12
                                      13
                                      14
                                      15
                                      16
                                      17
                                      18
                                      19
                                      20
                                      21
                                      22
                                      23
                                      24
                                      25
                                      26
                                      27
                                      28
                                      29
                                      30
                                      31
                                      32
                                      33
                                      34
                                      35
                                      /////////////////////////////////////////////////////////////////////// // myConsoleApplication.h /////////////////////////////////////////////////////////////////////// #pragma once #include "CConsoleApplication.h" #include "../Utilities/CLogFile.h" #include "../Utilities/CTimer.h" /////////////////////////////////////////////////////////////////////// //  /////////////////////////////////////////////////////////////////////// class myConsoleApplication : public CConsoleApplication { // add pre Main initialisation procedures DECLARE_INITIALISE; public: myConsoleApplication (); virtual ~myConsoleApplication (); virtual int Main (int iNumArgs, char** apcArgs); private: utilities::CLogFile m_Log("global_log",LOG_ALL,1); //####### - error C2059: syntax error : 'string' utilities::CTimer m_Timer; }; /////////////////////////////////////////////////////////////////////// // implement the pre Main initialisation REGISTER_INITIALISE(myConsoleApplication);

                                      And heres a reduced class with zero functionality (but still the error)

                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      9
                                      10
                                      11
                                      12
                                      13
                                      14
                                      15
                                      16
                                      17
                                      18
                                      19
                                      20
                                      21
                                      22
                                      23
                                      24
                                      25
                                      26
                                      27
                                      28
                                      29
                                      30
                                      31
                                      32
                                      33
                                      34
                                      35
                                      36
                                      37
                                      38
                                      39
                                      40
                                      41
                                      42
                                      43
                                      44
                                      45
                                      46
                                      47
                                      48
                                      /////////////////////////////////////////////////////////////////////// // CLogFile /////////////////////////////////////////////////////////////////////// #pragma once #include <list> #include <string> #include <fstream> #include <ctime> #include <cstdio> #include <cstdarg> // add to the utilities namespace namespace utilities { /////////////////////////////////////////////////////////////////////// // types of valid log entry enum eLogEntryType { LOG_GENERAL = 0, LOG_WARNING, LOG_DEBUG, LOG_ALL }; /////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////// class CLogFile { /////////////////////////////////////////////////////////////////// public: CLogFile(const char * csName, eLogEntryType eLogPolicy = LOG_ALL, unsigned int uiFlushSize = 30) {}; }; /////////////////////////////////////////////////////////////////////// } // close utilities namespace /////////////////////////////////////////////////////////////////////// 

                                      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:

                                      1
                                      2
                                      3
                                      4
                                      myConsoleApplication () :m_log("global_log",LOG_ALL,1); .... utilities::CLogFile m_log;

                                      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.

                                      • 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 << " meters\n"; 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 files\microsoft visual studio 9.0\vc\include\istream(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?

                                      Понравилась статья? Поделить с друзьями:
                                    • Синтаксическая ошибка ожидается операнд неверный маркер bash
                                    • Синтаксическая ошибка идентификатор tchar
                                    • Синтаксическая ошибка непредвиденный токен требуется объявление
                                    • Синтаксическая ошибка идентификатор form1
                                    • Синтаксическая ошибка идентификатор file