Unknow error
I have this code below implement a simple Virtual Machine to load instruction and do things to data. The problem is the exception I throw when meet a » » at the begin of the instruction, or at the end. Or «,» in somewhere else in a string Instruction not the one between two registers. Please have a look at my work and help me figure out this problem, I really need your guys’ help.
|
|
Last edited on
When asking a question, please post code that will compile, or at least sort of compile. In your case, you left out all the include files, resulting in the output below from my compiler. I’m not willing to slog through that mess.
foo.cxx:9:5: error: ‘string’ does not name a type; did you mean ‘struct’? string code; ^~~~~~ struct foo.cxx:10:5: error: ‘string’ does not name a type; did you mean ‘struct’? string op1; ^~~~~~ struct foo.cxx:11:5: error: ‘string’ does not name a type; did you mean ‘struct’? string op2; ^~~~~~ struct foo.cxx:31:15: error: ‘string’ has not been declared void move(string dest, string src) { ^~~~~~ foo.cxx:31:28: error: ‘string’ has not been declared void move(string dest, string src) { ^~~~~~ foo.cxx:48:17: error: ‘string’ has not been declared void output(string dest) { ^~~~~~ foo.cxx:55:15: error: ‘string’ has not been declared void load(string instruction) { ^~~~~~ foo.cxx:88:5: error: expected ‘}’ at end of input } ^ foo.cxx: In member function ‘void VM::move(int, int)’: foo.cxx:32:30: error: request for member ‘substr’ in ‘dest’, which is of non-class type ‘int’ int idxd = stoi(dest.substr(1))-1; ^~~~~~ foo.cxx:32:20: error: ‘stoi’ was not declared in this scope int idxd = stoi(dest.substr(1))-1; ^~~~ foo.cxx:33:18: error: invalid types ‘int[int]’ for array subscript if (src[0] == 'R') ^ foo.cxx:35:33: error: request for member ‘substr’ in ‘src’, which is of non-class type ‘int’ int idxs = stoi(src.substr(1))-1; ^~~~~~ foo.cxx: In member function ‘void VM::output(int)’: foo.cxx:49:25: error: request for member ‘substr’ in ‘dest’, which is of non-class type ‘int’ int idx = stoi(dest.substr(1))-1; ^~~~~~ foo.cxx:49:15: error: ‘stoi’ was not declared in this scope int idx = stoi(dest.substr(1))-1; ^~~~ foo.cxx:50:9: error: ‘cout’ was not declared in this scope cout<< reg[idx].data; ^~~~ foo.cxx: In member function ‘void VM::load(int)’: foo.cxx:57:39: error: request for member ‘length’ in ‘instruction’, which is of non-class type ‘int’ char* cstr = new char[instruction.length()+1]; ^~~~~~ foo.cxx:58:29: error: request for member ‘c_str’ in ‘instruction’, which is of non-class type ‘int’ strcpy(cstr,instruction.c_str()); ^~~~~ foo.cxx:58:5: error: ‘strcpy’ was not declared in this scope strcpy(cstr,instruction.c_str()); ^~~~~~ foo.cxx:58:5: note: suggested alternative: ‘struct’ strcpy(cstr,instruction.c_str()); ^~~~~~ struct foo.cxx:60:17: error: ‘strtok’ was not declared in this scope char* token=strtok(cstr,cma); ^~~~~~ foo.cxx:60:17: note: suggested alternative: ‘static’ char* token=strtok(cstr,cma); ^~~~~~ static foo.cxx:61:9: error: ‘struct Instruction’ has no member named ‘code’ ins.code=string(token); ^~~~ foo.cxx:61:14: error: ‘string’ was not declared in this scope ins.code=string(token); ^~~~~~ foo.cxx:61:14: note: suggested alternative: ‘struct’ ins.code=string(token); ^~~~~~ struct foo.cxx:67:26: error: ‘NULL’ was not declared in this scope token=strtok(NULL,cma); ^~~~ foo.cxx:70:17: error: ‘struct Instruction’ has no member named ‘op1’ ins.op1=string(token); ^~~ foo.cxx:72:17: error: ‘struct Instruction’ has no member named ‘op2’ ins.op2=string(token); ^~~ foo.cxx:74:24: error: ‘out_of_range’ is not a member of ‘std’ throw std::out_of_range("Invalid Instruction");//the VS compiler said the error came from here ^~~~~~~~~~~~ foo.cxx: In member function ‘void VM::exec()’: foo.cxx:84:11: error: ‘struct Instruction’ has no member named ‘code’ if (ins.code == "Move") this->move(ins.op1, ins.op2); ^~~~ foo.cxx:84:42: error: ‘struct Instruction’ has no member named ‘op1’ if (ins.code == "Move") this->move(ins.op1, ins.op2); ^~~ foo.cxx:84:51: error: ‘struct Instruction’ has no member named ‘op2’ if (ins.code == "Move") this->move(ins.op1, ins.op2); ^~~ foo.cxx:85:16: error: ‘struct Instruction’ has no member named ‘code’ else if (ins.code == "Output") this->output(ins.op1); ^~~~ foo.cxx:85:51: error: ‘struct Instruction’ has no member named ‘op1’ else if (ins.code == "Output") this->output(ins.op1); ^~~ foo.cxx: At global scope: foo.cxx:88:5: error: expected unqualified-id at end of input }
Okay, I added:
|
|
to the beginning, and
}
to the end and it compiles for me.
The problem is the exception I throw
//the VS compiler said the error came from here
Is this a compiler error, or a runtime error?
If runtime: You’re throwing an exception. We can’t see where you are calling the load function, so we have no idea how you are handling this exception. Do you ever catch this exception?
If compile-time, perhaps it’s flagging the fact that you have dead code or something, and your default settings make this an error instead of a warning.
— First, line 75 is dead code.
— Therefore, i is never incremented to 1 or beyond.
— Therefore, lines 71 to 76 are all dead code.
I am assuming that is not intentional, but you never told us what the actual error is.
With VS2019, this compiles OK at level 4 warnings with no errors/warnings:
|
|
Hmm yeah, g++ doesn’t warn that there is unreachable code, as well. Maybe it doesn’t bother warning on dead code within if-statements. Looks like the warning capabilities here are very limited. Sounds like OP’s issue is the runtime issue, then.
As my teacher said, any warning will be treat as error for his testcase, does this means that my code is wrong
The code produced no warnings at L4 compile with VS2019. This does not mean that your code is not wrong. It could well have logic and other run-time issues. You’ll need to test it and debug it as needed in order to ensure it works as required/expected.
Here the input and output of this exercise:
|
|
|
|
I had just edit my code but it always throw this error (the teacher compiler, not mine)
|
|
There is a place in your code where you most likely are doing:
throw "some string literal";
You should catch this exception via:
|
|
Or, the issue is that you should avoid the logic that causes the exception in the first place.
Last edited on
Topic archived. No new replies allowed.
Модератор: Модераторы разделов
-
_nic
- Сообщения: 384
- ОС: WinXP; OpenSUSE X86_64
Code::Blocks .Ничего непонимаю
Пробуй перенести небольшой код из MS VC 2008 Но при сборке получаю какуе то непонятную пургу
Код:
/home/user/Documents/mra/MRA/main.cpp||In function ‘int main()’:|
/home/user/Documents/mra/MRA/main.cpp|10|error: ‘SOCKET’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|10|error: expected `;' before ‘s’|
/home/user/Documents/mra/MRA/main.cpp|10|error: ‘SOCKADDR_IN’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|10|error: expected `;' before ‘adr’|
/home/user/Documents/mra/MRA/main.cpp|11|error: ‘hostent’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|11|error: ‘h’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|14|error: ‘memset’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|15|error: ‘gethostbyname’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|17|error: ‘adr’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|18|error: ‘inet_addr’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|19|error: ‘htons’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|20|error: ‘s’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|20|error: ‘IPPROTO_TCP’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|23|error: ‘closesocket’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|26|error: ‘strtok’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|27|error: ‘strstr’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|27|error: ‘strcpy’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|29|error: ‘atoi’ was not declared in this scope|
/home/user/Documents/mra/MRA/main.cpp|34|error: ‘strlen’ was not declared in this scope|
||=== Build finished: 19 errors, 0 warnings ===|
WTF? Я все нужные заголовки подключил ведь
Код: Выделить всё
#include <iostream>
#include <curses.h>
#include <sys/types.h>
#include <sys/socket.h>
-
watashiwa_daredeska
- Бывший модератор
- Сообщения: 4038
- Статус: Искусственный интеллект (pre-alpha)
- ОС: Debian GNU/Linux
Re: Code::Blocks .Ничего непонимаю
Сообщение
watashiwa_daredeska » 20.10.2009 23:58
Что такое ‘SOCKET’? Это откуда вообще?
man gethostbyname:
#include <netdb.h>
extern int h_errno;struct hostent *gethostbyname(const char *name);
Где этот инклуд?
strcpy и прочие str* вообще в string.h, но если уж у Вас #include <iostream>, то в <cstring> и про неймспейс std не забыть.
-
_nic
- Сообщения: 384
- ОС: WinXP; OpenSUSE X86_64
Re: Code::Blocks .Ничего непонимаю
Сообщение
_nic » 21.10.2009 01:10
Теперь такие ошибки
/home/user/Documents/mra/MRA/main.o||In function `main’:|
main.cpp:(.text+0x379)||undefined reference to `stdscr’|
main.cpp:(.text+0x37e)||undefined reference to `wgetch’|
||=== Build finished: 2 errors, 0 warnings ===|
Я нагуглил что надо «добавить к флагам компиляции -lcurses».Как это настроить в Code::Blocks ?
Table of Contents
Common G++ Errors
Summary
This is a guide to help you CS35ers make sense of g++ and its often cryptic error messages.
If you discover an error not listed here feel free to edit this wiki,
or send your error along with source code and an explanation to me — grawson1@swarthmore.edu
Weird Errors
If you are getting strange compiler errors when your syntax looks fine, it might be a good idea to check that your Makefile is up to date
and that you are including the proper .h files. Sometimes a missing } or ; or ) will yield some scary errors as well.
Lastly, save all files that you might have changed before compiling.
Bad Code Sample
What’s wrong with the following code? (Hint: there are two errors)
#include<iostream> using namespace std; int main(){ int foo; for(int i = 0, i<100, i++) { foo++; cout << foo << endl; } return 0; }
When compiled this yields:
junk.cpp:9: error: expected initializer before '<' token
junk.cpp:13: error: expected primary-expression before 'return
‘
junk.cpp:13: error: expected `;' before 'return
‘
junk.cpp:13: error: expected primary-expression before 'return
‘
junk.cpp:13: error: expected `)' before 'return
‘
First, the parameters of the for
loop need to be separated by semicolons, not commas.
for(int i = 0; i<100; i++) { foo++; cout << foo << endl; }
Now look at this sample output of the corrected code:
-1208637327
-1208637326
-1208637325
-1208637324
-1208637323
-1208637322
Why the weird values? Because we never initialized foo
before incrementing it.
int foo = 0;
‘cout’ was not declared in this scope
Two things to check here:
(1) Did you add
#include<iostream>
to your list of headers?
(2) Did you add
using namespace std;
after your #includes?
‘printf’ was not declared in this scope
Add
#include<cstdio>
to your list of headers. Note if you are coming from C programming, adding
#include<cstdio> is preferred in C++ over #include <stdio.h>.
Cannot Pass Objects of non-POD Type
junk.cpp:8: warning: cannot pass objects of non-POD type 'struct std::string' through '…'; call will abort at runtime
junk.cpp:8: warning: format '%s' expects type 'char*', but argument 2 has type 'int
‘
What this usually means is that you forgot to append .c_str() to the name of your string variable when using printf.
This error occurred when trying to compile the following code:
int main(){ string foo = "dog"; printf("This animal is a %s.n",foo); return 0; }
Simply appending to .c_str() to “foo” will fix this:
printf("This animal is a %s.n",foo.c_str());
The reason you got this error is because printf is a C function and C handles strings differently than C++
Invalid Use of Member
junk.cpp:8: error: invalid use of member (did you forget the '&' ?)
What this usually means is that you forget to add () to the end of a function call.
Ironically, every time I see this it is never because I forgot the ‘&’.
This error occurred when trying to compile the following code:
int main(){ string foo = "dog"; printf("This animal is a %s.n",foo.c_str); return 0; }
Simply adding the open and close parentheses () will take care of this for you:
printf("This animal is a %s.n",foo.c_str());
Request for Member ‘Foo’ in ‘Bar’, which is of non-class type ‘X’
trycredit.cpp:86: error: request for member 'print' in 'card', which is of non-class type 'CreditCard*
‘
What this usually means is that you are using a ‘.’ between the class pointer and the function you are trying to call.
Here is an example from the CreditCard lab:
void useCard(CreditCard *card, int method) { //Used to access the methods of the class if (method==1) { card.print(); }
Since card
is a CreditCard* we need → rather than . Fixed:
if (method==1) { card->print(); }
Undefined Reference to V Table
This error usually means you need to add a destructor to your myClass.cpp/myClass.inl code.
If you don’t want to implement a real destructor at this point, you can write something like this:
myClass::~myClass(){}
So long as the destructor exists, you should now be able to compile fine. Of course,
implement a real destructor at a later point.
SergeyKagen 3 / 4 / 2 Регистрация: 02.04.2018 Сообщений: 315 |
||||
1 |
||||
19.04.2019, 22:16. Показов 132175. Ответов 14 Метки нет (Все метки)
Простой код, но Arduino IDE напрочь отказывается принимать переменные. Что за глюк или я что-то неправильно делаю?
ошибка при компиляции «‘count’ was not declared in this scope», что не так?
__________________
0 |
marat_miaki 495 / 389 / 186 Регистрация: 08.04.2013 Сообщений: 1,688 |
||||
19.04.2019, 23:26 |
2 |
|||
Решение
1 |
Lavad 0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
||||||||
14.09.2019, 22:33 |
3 |
|||||||
Доброго времени суток!
В loop() делаю вызов:
При компиляции выделяется этот вызов, с сообщением: ‘myDisplay’ was not declared in this scope Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции P.S. Код, что использовал в качестве функции, работоспособен. Раньше находился в loop(). Скетч постепенно разрастается, много однотипных обращений к дисплею…
0 |
8385 / 6147 / 615 Регистрация: 10.12.2010 Сообщений: 28,683 Записей в блоге: 30 |
|
14.09.2019, 23:57 |
4 |
Создал функцию (за пределами setup и loop), Перевидите на нормальный язык. В другом файле что ли? Добавлено через 1 минуту
Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции Читать учебники по С++ не пробовали? https://metanit.com/cpp/tutorial/3.1.php Специфика Arduino лишь отличается тем что пред объявления не всегда нужны. Добавлено через 7 минут
0 |
ValeryS Модератор 8759 / 6549 / 887 Регистрация: 14.02.2011 Сообщений: 22,972 |
||||
15.09.2019, 00:09 |
5 |
|||
Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции это где ж такое написано?
а объявить уже в удобном месте
0 |
0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
|
15.09.2019, 00:48 |
6 |
Неделю назад ВПЕРВЫЕ включил Arduino Uno. Написал на том же языке, что и читал на всяких форумах и справочниках по Arduino :-). За пределами этих функций — значит не внутри них. Обе приведенных Вами ссылок просмотрел, проверил в скетче… В итоге вылезла другая ошибка: void myDisplay(byte x, byte y, char str) тоже пробовал. Та же ошибка. Что не так на этот раз?
0 |
Модератор 8759 / 6549 / 887 Регистрация: 14.02.2011 Сообщений: 22,972 |
|
15.09.2019, 01:26 |
7 |
В итоге вылезла другая ошибка: точку с запятой в конце поставил?
1 |
Lavad 0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
||||||||||||
15.09.2019, 08:46 |
8 |
|||||||||||
Вот скетч. Проще некуда.
Любое из трех так называемых «объявлений» (строки 7…9) выдает одну и ту же ошибку — я пытаюсь объявить функцию как переменную. Добавлено через 9 минут
Компилятор задумался (я успел обрадоваться), но, зараза :-), он снова поставил свой автограф undefined reference to `myDisplay(unsigned char, unsigned char, char, float) На этот раз он пожаловался на строку вызова функции. Добавлено через 34 минуты
Dispay вместо Display Добавлено через 8 минут
0 |
ValeryS Модератор 8759 / 6549 / 887 Регистрация: 14.02.2011 Сообщений: 22,972 |
||||||||
15.09.2019, 10:36 |
9 |
|||||||
void myDisplay(byte, byte, char, float) = 0; вот так не надо делать(приравнивать функцию к нулю) Добавлено через 5 минут
void myDispay(byte x, byte y, char str, float temp)
myDisplay(0, 0, «C», temp); просишь чтобы функция принимала символ
или проси передавать строку, например так
1 |
Avazart 8385 / 6147 / 615 Регистрация: 10.12.2010 Сообщений: 28,683 Записей в блоге: 30 |
||||
15.09.2019, 12:02 |
10 |
|||
Кроме того наверное лучше так:
Тогда можно будет вынести ф-цию в отдельный файл/модуль.
1 |
locm |
15.09.2019, 21:07
|
Не по теме:
Arduino Uno.
AVR (Basic, немного Assembler). Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.
0 |
Avazart |
15.09.2019, 21:21
|
Не по теме:
Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере. Но лучше не надо …
0 |
Lavad 0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
||||
16.09.2019, 12:12 |
13 |
|||
это где ж такое написано? Оказалось, что я верно понял чтиво по справочникам:
вот так не надо делать(приравнивать функцию к нулю)… Методом проб и ошибок уже понял :-).
или передавай символ… Если передаю в одинарных кавычках более одного символа, а функция ждет как
или проси передавать строку, например так… Буквально вчера попалось это в справочнике, но как-то не дошло, что тоже мой вариант :-).
Кроме того наверное лучше так:
Тогда можно будет вынести ф-цию в отдельный файл/модуль. Благодарю за совет! Как-нибудь проверю…
0 |
8385 / 6147 / 615 Регистрация: 10.12.2010 Сообщений: 28,683 Записей в блоге: 30 |
|
16.09.2019, 12:54 |
14 |
Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции Нафиг выкиньте эти справочники.
0 |
0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
|
16.09.2019, 13:00 |
15 |
Ссылки Ваши добавлены в закладки. Время от времени заглядываю.
0 |