Ошибка expected at end of input

I have moved from Java to CPP and am struggling to wrap my head around structuring constructor chaining, which I think is the sourceof my issues.

My header file is as follows:

public:
GuidedTour();
GuidedTour(string ID, string desc, double fee, int size, string guide, string date)
            : Tour(ID, desc, fee);

And my cpp file is as follows:

 GuidedTour(string ID, string desc, double fee, int size, string guide, string date)
            : Tour(ID, desc, fee) {
                this->tourSize = size;
                this ->tourGuide = guide;
                this -> tourDate = date;
                }

I am getting two errors:

guided_tour.h: In constructor 'GuidedTour::GuidedTour(std::string, std::string, double, int, std::string, std::string)':
guided_tour.h:17:25: error: expected '{' at end of input
guided_tour.cpp: At global scope:
guided_tour.cpp:5:19: error: expected ')' before 'ID'

Any insight here would be much appreciated!

Лизаветка

1 / 1 / 0

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

Сообщений: 34

1

01.05.2017, 21:41. Показов 38353. Ответов 13

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


Студворк — интернет-сервис помощи студентам

Посмотрите, пожалуйста. Выдает ошибку expected ‘}’ at end of input, но скобки везде попарно

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
int main()
{
    setlocale(LC_ALL, "Russian");
    inform();
    getch();
    system("cls");//новая страница
    char zapros_menu, vspom_zapr;
    glavnoe_menu();
    vspom_zapr=zapr_menu();
    int otvet;
    while (vspom_zapr!='0')
    {
        zapros_menu=vspom_zapr;
        system("cls");
        switch (zapros_menu)
        {
        case '1':
            {
                svedenia_po_program();
            }
        case '2':
            {
                otvet=TEORIA::demonstrate();
            }
        case '3':
            {
 
            }
        case '4':
            {
 
            }
        case '5':
            {
 
            }
        };
        getch();
        system("cls");
        glavnoe_menu();
        if (otvet==0)
        {
            vspom_zapr=0;
        } else
        {
            vspom_zapr=zapr_menu();
        };
    };
    return 0;
}



0



Джоуи

1073 / 635 / 240

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

Сообщений: 3,546

Записей в блоге: 2

01.05.2017, 21:53

2

а на какой строке вылетает ошибка?



0



284 / 232 / 114

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

Сообщений: 584

01.05.2017, 21:57

3

привыкайте нормально код форматировать. черт ногу сломит в такой писанине.
по ошибке: если это студия и в начале файла нет #include «stdafx.h» — то в этом может быть причина.
может есть другой код, который вы не написали тут, но он есть. например тут нед вообще ни
одного инклуда, что там у вас еще есть, чего вы не запостили известно только вам.



0



Джоуи

1073 / 635 / 240

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

Сообщений: 3,546

Записей в блоге: 2

01.05.2017, 21:59

4

Во-первых, если операция только одна, то операторные скобки необязательны (хотя бы не запутаетесь)
Во-вторых, так как Вы не привели полный код программы, откуда нам знать, что эта ошибка не возникает во всяких подпрограммах типа zapr_menu()?



0



Лизаветка

1 / 1 / 0

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

Сообщений: 34

01.05.2017, 22:07

 [ТС]

5

вот полный код программы, выдает ошибку в последней строке, пробовала убирать частично код программы, ошибка уходит, если только убрать строки #include «teoria.h» и #include «teoria.cpp, выходит ошибка в них

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <iostream>
#include <fstream>
#include <conio.h>
#include <stdlib.h>
#include <string>
 
#include "teoria.h"
 
#include "teoria.cpp"
 
using namespace std;
 
void inform()
{
    cout << "n"
    "        Астраханский государственный технический университетn"
    "          Институт Информационных технологий и коммуникацийnnn"
    "                                                Кафедраn"
    "                                                Автоматизированных системn"
    "                                                бработки информации и управленияnnnnn"
    "                     Курсовая работа по дисциплинеn"
    "                   'Программирование и информатика'n"
    "        Учебно - демонстрационная программа <<Сортировка Бэтчера>>nnnn"//свет
    "                                                Выполнила: студентка группы ДИНРб-11n"
    "                                                Бондаренко Е. М.n"//свет
    "                                                Руководитель работыn"
    "                                                Ст. преп. Толасова В. В.nnnnn"
    "                          г.АСТРАХАНЬ  2017г.nn ";
};
 
void glavnoe_menu()
{
    cout << "nn     Учебно-демонстрационная программа <<Cортировка Бэтчера>> n";//свет
    cout << "nnn*************************";
    cout << "<Главное Меню>";//свет
    cout <<    "****************************nn" <<endl;
    cout << "                                                   клавишаnn";
    cout << "            Сведения о работе программы..............";
    cout << " 1nn";//свет
    cout << "            Теоретический материал...................";
    cout << " 2nn";//свет
    cout << "            Пошаговая демонстрация сортировки........";
    cout << " 3nn";//свет
    cout << "            Тест по пройденному материалу............";
    cout << " 4nn";//свет
    cout << "            Зайти как администратор..................";
    cout << " 5nn";//свет
    cout << "            Выход....................................";
    cout << " 0nn";//свет
};
 
char zapr_menu()
{
    char zapr;
    cin >> zapr;
    while (zapr!='0' && zapr!='1' && zapr!='2' && zapr!='3' && zapr!='4' && zapr!='5')
    {
        cout << "nНекорректный ввод! Повторите!n";
        cin >> zapr;
    };
    return zapr;
};
 
void svedenia_po_program()
{
    ifstream out("svedenia.txt");
    if(out.is_open())
    {
        while (!out.eof())
        {
            string stroka;
            getline(out, stroka, 'n');
            cout << "n   " << stroka;
        }
    };
    out.close();
};
 
int main()
{
        setlocale(LC_ALL, "Russian");
    inform();
    getch();
    system("cls");//новая страница
    char zapros_menu, vspom_zapr;
    glavnoe_menu();
        vspom_zapr=zapr_menu();
         int otvet;
    while (vspom_zapr!='0')
        {
             zapros_menu=vspom_zapr;
             system("cls");
             switch (zapros_menu)
            {
            case '1':
                {
                       svedenia_po_program();
                }
            case '2':
               {
                      otvet=TEORIA::demonstrate();
                }
            case '3':
               {
 
                }
            case '4':
               {
 
                }
             case '5':
               {
 
                }
        };
        getch();
        system("cls");
        glavnoe_menu();
        if (otvet==0)
        {
            vspom_zapr=0;
        } else vspom_zapr=zapr_menu();
    };
    return 0;
}



0



Джоуи

1073 / 635 / 240

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

Сообщений: 3,546

Записей в блоге: 2

01.05.2017, 22:11

6

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

#include «teoria.cpp»

что значит #include исходный код C++? Вы подключаете и хедер teoria.h и исходник teoria.cpp



0



Джоуи

1073 / 635 / 240

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

Сообщений: 3,546

Записей в блоге: 2

01.05.2017, 22:12

7

И учитесь уже обрамлять код тегами [CPP]

Миниатюры

ошибка expected '}' at end of input
 



0



1 / 1 / 0

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

Сообщений: 34

01.05.2017, 22:15

 [ТС]

8

спасибо, впредь буду оформлять нормально, это мои первые 15 минут на данном форуме)



0



Джоуи

1073 / 635 / 240

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

Сообщений: 3,546

Записей в блоге: 2

01.05.2017, 22:16

9

Лизаветка, ну а насчет инклюдов Вы поняли?



0



Лизаветка

1 / 1 / 0

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

Сообщений: 34

01.05.2017, 22:20

 [ТС]

10

нет. я подключаю и то и то, без хедера ошибка остается.
вот что у меня представляет teoria.cpp

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "teoria.h"
 
#include <iostream>
#include <fstream>
#include <ctime>
#include <conio.h>
#include <windows.h>
 
using namespace std;
 
namespace TEORIA
{
 
    void mini_menu()
    {
        cout << "nn                                          клавишаnn";
        cout << "            Назад...........................";
        cout << " 1n";//свет
        cout << "            Вперед..........................";
        cout << " 2n";//свет
        cout << "            Главное меню....................";
        cout << " 3n";//свет
        cout << "            Выход...........................";
        cout << " 0n";//свет
    }
 
    char numb_menu()
    {
        char zap;
        cin >> zap;
        while(zap!='1' && zap!='2' && zap!='3' && zap!='0')
        {
            cout << "nНекорректный ввод! Повторите!n";
            cin >> zap;
        };
        return zap;
    }
 
    void display_str(char* name)
    {
        ifstream str(name);
        if(str.is_open())
        {
            while (!str.eof())
            {
                string stroka;
                getline(str, stroka, 'n');
                cout << "n   " << stroka;
            }
        };
        str.close();
    }
 
    int demonstrate()
    {
        char dop_zapr='1';
        char zapros_menu='1';
        int otvet;
        do
        {
            switch (dop_zapr)
            {
            case '1':
                {
                    char name[20]="teor_1.txt";
                    display_str(name);
                }
            case '2':
                {
                    char name[20]="teor_2.txt";
                    display_str(name);
                }
            case '3':
                {
                    char name[20]="teor_3.txt";
                    display_str(name);
                }
            case '4':
                {
                    char name[20]="teor_4.txt";
                    display_str(name);
                }
            }
            mini_menu();
            zapros_menu=numb_menu();
            if (zapros_menu=='1')
            {
                dop_zapr++;
            } else dop_zapr--;
        } while (zapros_menu!='3' && zapros_menu!='0' && dop_zapr!='5' && dop_zapr!='0');
        if (zapros_menu=='0') otvet=0; else otvet=1;
        return otvet;
}

и вот teoria.h

C++
1
2
3
4
5
6
7
8
9
10
11
#ifndef TEORIA_H_INCLUDED
#define TEORIA_H_INCLUDED
 
namespace TEORIA
{
    void mini_menu();
    char numb_menu();
    void display_str(char name);
    int demonstrate();
}
#endif // TEORIA_H_INCLUDED

Что нужно убрать?



0



Джоуи

1073 / 635 / 240

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

Сообщений: 3,546

Записей в блоге: 2

01.05.2017, 22:22

11

Лизаветка, вопрос остается прежним: на какой строке и в каком файле возникает ошибка? Можно скриншот скинуть, если сами не разбираетесь



0



DU3

284 / 232 / 114

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

Сообщений: 584

01.05.2017, 22:24

12

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

Решение

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

C++
1
2
namespace TEORIA
{



1



Joey

01.05.2017, 22:29

Не по теме:

DU3, ждем ебилдов ТС



0



1 / 1 / 0

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

Сообщений: 34

01.05.2017, 22:35

 [ТС]

14

Спасибо за ответы) ошибка выволилась на последней строке основной программы, оказалось нет закрывабщейся скобки в файле teoria.cpp , спасибо за вопросы, буду работать над оформлением��



1



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

01.05.2017, 22:35

Помогаю со студенческими работами здесь

Ошибка: Expected END but received ELSE
Всем привет , кто может помочь?!) строка 59 ругается на else. (expected END but received ELSE).

Ошибка: ‘END’ expected but ‘ELSE’ found
Задание:
Написать программу, которая бы по введенному номеру времени года (1 — зима, 2 — весна, 3…

Ошибка: ‘END’ expected but ‘UNTIL’ found
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,…

Ошибка ‘Expected END but recieved’
Понимаю,что ошибка связанная с begin и end,но я не догоняю,где пропущеноunit Unit2;

interface

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

14

Your code is completely wrong in almost every respect.


#define char incomingByte; //Defines incomingByte 

That line means that the compiler will substitute incomingByte; whenever it sees char.


#define char sendBack = K;

Now it will substitute sendBack = K; when it sees char.


#define char ?;

Now it will substitute ?; when it sees char.


#define pollTime;

I don’t know what you are thinking here. If you are trying to declare a variable you have to give a type, like this:

int pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}
void loop() {

Those lines are OK.


for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.

You don’t want the semicolon there. A for loop is not written like that. You possibly mean while, ie.

while(Serial.available() > 0) 

pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.

That is doing nothing of the sort. It is delaying 200 µs, it isn’t setting anything.


incomingByte  = Serial.read();

That line is OK, assuming you declared incomingByte like this, and not the way you did:

char incomingByte; 

if(incomingByte = ?) {

That needs to be in single quotes, as you are comparing a character. Also you compare with == not = ie.

if(incomingByte == '?') {

Serial.print(sendBack);

It looks from your earlier code you mean:

Serial.print('K');

  }
 }
}  

These lines look OK.


I suggest you read a beginners page about C programming. This is just pure guesswork what you are doing here. For one thing, read up on how #define works. Here is one page: https://www.techonthenet.com/c_language/constants/create_define.php. And another: http://www.cprogramming.com/reference/preprocessor/define.html

Arduino Forum

Loading

The expected declaration or statement at end of input error always affects programs and documents when developers forget to include a symbol at the end of the function. Henceforth, professional programmers refer to it as a syntax error because it messes up the expected declaration, launching the error.expected declaration or statement at end of input

Therefore, our experts wrote this profound guide featuring many examples that recreate the error expected in your system and teach the finest solutions. In addition, you will understand more about this annoying mistake when you finish reading all chapters in this in-depth guide, so let us begin the journey.

Contents

  • What Causes the Expected Declaration or Statement at End of Input?
    • – Writing an Incorrectly Indented Code
    • – Facing Issues Locating the Brackets
  • Debugging the Expected Declaration or Statement: Repeat These Steps
    • – Initializing the Valid Commands
  • Conclusion

Your system causes an expected statement or declaration at the end of an input when your document or code needs to have correct symbols at the end of the function. Consequently, the program can’t render the processes correctly, halting your project and file.

In addition, although it is rare for professional developers to experience this bug, it can affect any script because mistakes occur when writing long codes. But the good part is that many users believe debugging this syntax error is easy because including a symbol such as a bracket or a comma is not time-consuming.

However, finding the possible culprit is more challenging than fixing the syntax because your code can have several incorrectly written commands without apparent indicators. Henceforth, our experts recommend scanning the code and fixing the obvious mistakes, although this does not guarantee the solution.

As a result, this guide includes several incorrect examples that reproduce the mistake, helping readers comprehend the possible reasons. In addition, we will use the same model to provide the debugging principles, although the syntax is not very different. However, our experts confirmed an exact mistake when misplacing some commands from the primary function, such as the return and null values. So, let us recreate this annoying mistake that blocks your system.

– Writing an Incorrectly Indented Code

This error’s first cause has several commands that need more adequate closing brackets. For example, developers must close the primary and secondary orders to clarify the purpose and the code line where the function ends. Unfortunately, writing an incorrectly indented code is messy, and programmers need help locating the mistake quickly, as you will soon learn. This might severely affect your project and system.Expected Declaration or Statement at End of Input Causes

The following example includes an incorrect code:

#include <stdio.h>

#include <stdlib.h>

struct node{

char data [64];

struct node *next;

};

struct node *first, *current, *new;

int main (void)

{

int k;

scanf (“%d”, &k);

struct node *head = NULL;

do{

switch (k) {

case 1: addnew();

break;

} while (k!=0);

void addnew (void)

{

struct node *newnode = malloc (sizeof (struct node));

if (head = NULL)

first=new=current;

else

{

Current = first;

while (current -> next! = NULL)

current = current -> next;

current -> next = new;

current = new;

}

Gets (current -> data);

Current -> next = NULL;

}

As you can tell, although the elements, tags, and values in this example are correct, the document does not have adequate closing brackets. In addition, the current and new commands include dependencies, which is critical when writing complex documents and applications. Unfortunately, the mistake can affect other scripts and syntaxes due to the exact reason. You can learn more about the last invalid script in the following chapter before we teach the most sophisticated debugging methods.

– Facing Issues Locating the Brackets

Although the mistake is obvious and developers can fix it quickly, several scripts include values that appear full-proof, yet the system launches the error. Henceforth, our experts will show you an example of a complex code with a single code line and function that does not have a closing bracket. We will not tell you the process that lacks the closing symbol so you can attempt to pinpoint it. In addition, this example includes correct indentation and values.

Please read the following example that has a single incorrect command:

#include <stdio.h> // It includes

#include <stdlib.h>

#define PION_BLANC 1

#define PION_BLACK -1

#define CASE_EMPTY 0

//////////////////////////:::::::::::::::::::::::::::::::::::::::::

void attach_ligne (int i,int merelle[7][7]) {

int j;

printf (” %2d “,i+1);

for (j=0;j<7;j++) {

switch (bird [i][j]){

case PION_BLANC:

printf (” O “);

break;

case PION_BLACK:

printf (” X “);

break;

case CASE_EMPTY:

printf (” [ ] “);

break;

default:

printf (“______”);

break;

}

}

Printf (“| %2dn”,i+1);

Printf (” |—————————————–|n”);

void attach_damier (int bird[7][7]) {

int i;

printf (” 1 2 3 4 5 6 7 n”);

printf (” |—————————————–|n”);

for (i=0;i<7;i++)

attach_ligne (i, bird);

printf (” 1 2 3 4 5 6 7 n”);

}

int main()

{

int bird [7][7] = {{0}};

attach_damier (bird);

return 0;

}

This example confirms that a single command can ruin the entire document. Therefore, developers and programmers must react quickly and implement the debugging principles in this guide. We suggest reading the following chapter because it teaches the most optimal solutions for this mistake.

Debugging the Expected Declaration or Statement: Repeat These Steps

You can debug the expected declaration by writing the functions with proper opening and closing brackets. In technical langue, you have to use a single bracket while introducing the struct node and single dependency in your code in order to fix it.



However, the examples in the previous sections confirmed that locating the functions is only sometimes straightforward. Still, programmers must scan the entire syntax to pinpoint the syntax error, no matter how time-consuming this is. Henceforth, we will show you a short code snippet that launches the mistake before fixing the values.

The following example introduces a simple command:

#include <stdio.h>

int main (void){

printf (“Hello everyone”);

return 0;

Although everything looks perfect to less experienced developers, the system launches an invalid message, confirming the lack of fair brackets. So, programmers will likely experience the following message:

prog.c: In function ‘main’:

prog.c:4:1: error: expected declaration or statement at end of input

return 1;

^~~~~~

This invalid snippet helps users understand the exact location and implement their solution.

So, we suggest repeating the following code to debug your script and remove the error:

#include <stdio.h>

int main (void){

printf (“Hello everyone”);

return 0;

}

The last symbol closes the primary function, helping your computer understand the purpose. Consequently, any subsequent operations must follow the same syntax. However, this guide includes another practical solution that debugs your document.

– Initializing the Valid Commands

This section fixes the incorrect code from the second chapter with more complex properties. Therefore, we will take a short code snippet to analyze the inconsistencies.Initializing the Valid Commands

This snippet is an infinite loop, which is incorrect:

int main(void)

{

int k;

scanf (“%d”, &k);

struct node *head=NULL;

do {

switch (k) {

case 1:

addnew();

break;

}

} while (k!=0);

However, developers must wait to modify the k value before the primary call.

So, we must introduce a struct node and a single dependency with a single bracket, as shown below:

void addnew(void)

{

struct node *newnode = malloc (sizeof (struct node));

if (head=NULL)

first=new=current;

The void and the = symbol are assignments that test the code’s equality. To top it all off, this example does not have correct closing brackets.

Instead, your code should look like this:

else

{

Current = first;

While (current -> next!=NULL)

Current = current -> next;

Current -> next = new;

Current = new;

}

Gets (current -> data);

Current -> next = NULL;

}

Moreover, our experts suggest initializing the valid commands to clarify any imperfections further. So, this example confirms nothing should stop you from fixing this mistake on your computer.

Conclusion

Your computer launches an expected statement or declaration at the end of an input when your document or code needs to have correct symbols at the end of the function. In addition, this comprehensive guide explained and exemplified the following critical points:

  • Any commands and tasks that lack good opening and closing brackets will launch this annoying mistake
  • Indenting your code is vital when locating the error because it looks organized
  • Finding the mistake is sometimes time-consuming but is worth it because you will enable all processes
  • The mistake will not disappear unless developers write closing brackets for all leading and secondary commands
  • The invalid message sometimes includes indicators for the error

Facing this error is not rare at all and even seasoned developers are prone to it. So, there’s no need to overwhelm yourself because if you follow this guide step-by-step you will be able to overcome this challenge quite efficiently.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Возможно, вам также будет интересно:

  • Ошибка euro truck simulator 2 прекращена работа программы
  • Ошибка expected asm or attribute before token
  • Ошибка euro truck simulator 2 мод
  • Ошибка expected a file name
  • Ошибка euro truck simulator 2 steam что это

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

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