Error strtok was not declared in this scope

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.

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
#define _CRT_SECURE_NO_WARNINGS

#include <string>
#include <iostream>
#include <cstring>
using namespace std;
 enum DataType { NONE, INT };

struct GReg {
    int data;
    DataType type;
};

struct Instruction {
    string code;
    string op1;
    string op2;
};

class VM {
private:
    int IP; // IP register
    GReg reg[7]; // General register: R1 -> R7
    Instruction codeMemory[20];
    int codeLoadedIndex;
    
public:
    VM() { 
        this->IP = 0;
        for (int i = 0; i < 7; i++) {
            reg[i].type = NONE;
        }
        this->codeLoadedIndex = 0;
    }
    
    // Your student code here
    void move(string dest, string src) {
        int idxd = stoi(dest.substr(1))-1;
        if (src[0] == 'R')
        {
            int idxs = stoi(src.substr(1))-1;
            reg[idxd].data=reg[idxs].data;
            reg[idxd].type=reg[idxs].type;
        }
        else 
        {
            int tmp = stoi(src);
            reg[idxd].data=tmp;
            reg[idxd].type=INT;
        }
        IP++;
    }
    
    void output(string dest) {
    int idx = stoi(dest.substr(1))-1;
        cout<< reg[idx].data;
        IP++;
    
    }

    void load(string instruction) {
    Instruction ins;
    char* cstr = new char[instruction.length()+1];
    strcpy(cstr,instruction.c_str());
    char cma[]=" ,";
    char* token=strtok(cstr,cma);
    ins.code=string(token);
    int i=0;
        while (token)
        {
           
            //cout<<token<<endl;
            token=strtok(NULL,cma); 
            
            if (i == 0)
            ins.op1=string(token);
            else if (i==1)
            ins.op2=string(token);
            else throw "Invalid Instruction";
            i++;
            cout<<ins.op1<<" "<<ins.op2;
            
        }
    }

    void exec() {
        for (int i=0;i<codeLoadedIndex; i++){
		Instruction ins=codeMemory[i];
		if (ins.code == "Move") this->move(ins.op1, ins.op2);
		else if (ins.code == "Output") this->output(ins.op1);

	}
    }
    // End: Your student code here
    
    void dump() {
        cout << endl << "VM Info: " << endl;
        cout << "IP: " << this->IP << endl;
        for (int i = 0; i < 7; i++) {
            
            if (reg[i].type != NONE) {
                cout << "R" << i + 1 << ": " << reg[i].data << endl;
            }
        }
    }
};
int main()
{

}

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:

1
2
3
4
#include <string>
#include <iostream>
#include <cstring>
using namespace std;

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:

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
#define _CRT_SECURE_NO_WARNINGS

#include <string>
#include <iostream>
#include <cstring>
using namespace std;

enum DataType { NONE, INT };

struct GReg {
	int data;
	DataType type;
};

struct Instruction {
	string code;
	string op1;
	string op2;
};

class VM {
private:
	int IP; // IP register
	GReg reg[7]; // General register: R1 -> R7
	Instruction codeMemory[20];
	int codeLoadedIndex;

public:
	VM() {
		this->IP = 0;
		for (int i = 0; i < 7; i++) {
			reg[i].type = NONE;
		}
		this->codeLoadedIndex = 0;
	}

	// Your student code here
	void move(string dest, string src) {
		int idxd = stoi(dest.substr(1)) - 1;
		if (src[0] == 'R')
		{
			int idxs = stoi(src.substr(1)) - 1;
			reg[idxd].data = reg[idxs].data;
			reg[idxd].type = reg[idxs].type;
		} else
		{
			int tmp = stoi(src);
			reg[idxd].data = tmp;
			reg[idxd].type = INT;
		}
		IP++;
	}

	void output(string dest) {
		int idx = stoi(dest.substr(1)) - 1;
		cout << reg[idx].data;
		IP++;

	}

	void load(string instruction) {
		Instruction ins;
		char* cstr = new char[instruction.length() + 1];
		strcpy(cstr, instruction.c_str());
		char cma[] = " ,";
		char* token = strtok(cstr, cma);
		ins.code = string(token);
		int i = 0;
		while (token)
		{

			//cout<<token<<endl;
			token = strtok(NULL, cma);

			if (i == 0)
				ins.op1 = string(token);
			else if (i == 1)
				ins.op2 = string(token);
			else {
				throw std::out_of_range("Invalid Instruction");//the VS compiler said the error came from here
				i++;
			}

		}
	}

	void exec() {
		for (int i = 0; i < codeLoadedIndex; i++) {
			Instruction ins = codeMemory[i];
			if (ins.code == "Move") this->move(ins.op1, ins.op2);
			else if (ins.code == "Output") this->output(ins.op1);

		}
	}
};

int main()
{

}

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:

1
2
3
4
5
6
VM* vm = new VM();
vm->load("Move R1, 7");
vm->load("Output R1");
vm->exec();
vm->dump();
delete vm;

1
2
3
4
7
VM Info:
IP: 2
R1: 7

I had just edit my code but it always throw this error (the teacher compiler, not mine)

1
2
3
***Error***
terminate called after throwing an instance of 'char const*'
Aborted (core dumped)

There is a place in your code where you most likely are doing:
throw "some string literal";

You should catch this exception via:

1
2
3
4
5
6
7
8
try
{
    // existing code here
}
catch (const char* msg)
{
    std::cout << "Exception caught: " << msg << 'n';
}

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 напрочь отказывается принимать переменные. Что за глюк или я что-то неправильно делаю?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void setup() {
  
  Serial.begin(9600);
  int count = 0;
  pinMode(7, INPUT);
  pinMode(13, OUTPUT);
 
}
 
void loop() {
 
  if( digitalRead(7) == HIGH ){ 
    
    while(1){ 
      delayMicroseconds(2); 
      count++;  
      if( digitalRead(7) == LOW ){ Serial.println(count); count = 0; break; }
      }
    }  
}

ошибка при компиляции «‘count’ was not declared in this scope», что не так?

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



0



marat_miaki

495 / 389 / 186

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

Сообщений: 1,688

19.04.2019, 23:26

2

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

Решение

C++
1
2
3
4
5
6
7
8
  int count = 0; //глобальная переменная
 
  void setup() {
   Serial.begin(9600);
  pinMode(7, INPUT);
  pinMode(13, OUTPUT);
 
}



1



Lavad

0 / 0 / 0

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

Сообщений: 25

14.09.2019, 22:33

3

Доброго времени суток!
У меня то же сообщение, но на функцию :-(
Создал функцию (за пределами setup и loop), которая только принимает вызов, ничего не возвращает:

C++
1
2
3
4
5
void myDispay(byte x, byte y, char str) {
  lcd.setCursor(x, y);
  lcd.print(temp, 1);   // выводим данные, с точностью до 1 знака после запятой
  lcd.print(str);   // выводим писанину
  }

В loop() делаю вызов:

C++
1
myDisplay(0,0,"C");

При компиляции выделяется этот вызов, с сообщением:

‘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

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

Создал функцию (за пределами setup и loop),

Перевидите на нормальный язык.
Какие еще пределы?

В другом файле что ли?

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

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

Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции
Что делаю не так? В чем моя ошибка? Помогите, пожалуйста

Читать учебники по С++ не пробовали?

https://metanit.com/cpp/tutorial/3.1.php
http://cppstudio.com/post/5291/

Специфика Arduino лишь отличается тем что пред объявления не всегда нужны.

Добавлено через 7 минут
Кроме того иногда потеряй скобок {} приводят к таким ошибкам.



0



ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

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

Сообщений: 22,972

15.09.2019, 00:09

5

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

Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции

это где ж такое написано?
функцию нужно объявить перед первым вызовом, сиречь сверху
можно и просто декларировать сверху

C++
1
void myDispay(byte x, byte y, char str);

а объявить уже в удобном месте



0



0 / 0 / 0

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

Сообщений: 25

15.09.2019, 00:48

6

Неделю назад ВПЕРВЫЕ включил Arduino Uno.
Задолго до этого писал программы под Windows (БейсикВизуал) и AVR (Basic, немного Assembler). Т.е. имеется некоторое представление об объявлении переменных, функций,… От Си всегда держался как можно дальше. Это первая и последняя причина «нечитания» книг по Си. За неделю экспериментов на Arduino мнение об этом пока не изменилось — легче вернуться к Ассму, чем копаться в Си.

Написал на том же языке, что и читал на всяких форумах и справочниках по Arduino :-). За пределами этих функций — значит не внутри них.

Обе приведенных Вами ссылок просмотрел, проверил в скетче… В итоге вылезла другая ошибка:
function ‘void myDisplay(byte, byte, char)’ is initialized like a variable

void myDisplay(byte x, byte y, char str) тоже пробовал. Та же ошибка.

Что не так на этот раз? :-(



0



Модератор

Эксперт по электронике

8759 / 6549 / 887

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

Сообщений: 22,972

15.09.2019, 01:26

7

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

В итоге вылезла другая ошибка:
function ‘void myDisplay(byte, byte, char)’ is initialized like a variable

точку с запятой в конце поставил?



1



Lavad

0 / 0 / 0

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

Сообщений: 25

15.09.2019, 08:46

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
#include <PCD8544.h>
 
float temp = 0;
static PCD8544 lcd;   // даем имя подключенному дисплею (lcd)
static const byte Lm35Pin = 14;   // аналоговый пин (A0) Arduino, к которому подключен LM35
 
//void myDisplay() = 0;
//void myDisplay(byte, byte, char, float) = 0;
//void myDisplay(byte x, byte y, char str, float temp) = 0;
 
void myDispay(byte x, byte y, char str, float temp) {
  lcd.setCursor(x, y);   // начиная с (x,y)...
  lcd.print(temp, 1);   // выводим temp
  lcd.print(str);   // выводим писанину
}
 
void setup() {
  lcd.begin(84, 48);   // инициализируем дисплей
  analogReference(INTERNAL);   // подключаем внутренний ИОН на 1.1V
}
 
void loop() {
  float temp = analogRead(Lm35Pin) / 9.31;  // подсчитываем температуру (в Цельсиях)...
  myDisplay(0, 0, "C", temp);   // отправляем данные на экран
  delay(500);   // ждем 500 мсек
}

Любое из трех так называемых «объявлений» (строки 7…9) выдает одну и ту же ошибку — я пытаюсь объявить функцию как переменную.

Добавлено через 9 минут
Попробовал так:

C++
1
void myDisplay(byte x, byte y, char str, float temp);

Компилятор задумался (я успел обрадоваться), но, зараза :-), он снова поставил свой автограф :-)

undefined reference to `myDisplay(unsigned char, unsigned char, char, float)

На этот раз он пожаловался на строку вызова функции.

Добавлено через 34 минуты
Когда что-то новое затягивает, забываешь о нормальном отдыхе, теряешь концентрацию…
Нашел ошибку. Чистейшая грамматика

C++
1
void myDispay(byte x,...

Dispay вместо Display

Добавлено через 8 минут
ValeryS, благодарю за попытку помощи!



0



ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

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

Сообщений: 22,972

15.09.2019, 10:36

9

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

void myDisplay(byte, byte, char, float) = 0;

вот так не надо делать(приравнивать функцию к нулю)
так в классическом С++ объявляют чисто виртуальные функции, и класс в котором объявлена чисто виртуальная функция становится абстрактным. Означает что у функции нет реализации и в дочернем классе нужно обязательно реализовать функцию. А из абстрактного класса нельзя создать объект

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

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

void myDispay(byte x, byte y, char str, float temp)

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

myDisplay(0, 0, «C», temp);

просишь чтобы функция принимала символ char str, а передаешь строку "C"
или передавай символ

C++
1
myDisplay(0, 0, 'C', temp);

или проси передавать строку, например так

C++
1
void myDispay(byte x, byte y, char * str, float temp);



1



Avazart

Эксперт С++

8385 / 6147 / 615

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

Сообщений: 28,683

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

15.09.2019, 12:02

10

Кроме того наверное лучше так:

C++
1
2
3
4
5
6
7
8
void myDispay(PCD8544& lcd,byte x, byte y, char str, float temp) 
{
  lcd.setCursor(x, y);   // начиная с (x,y)...
  lcd.print(temp, 1);   // выводим temp
  lcd.print(str);   // выводим писанину
}
 
myDisplay(lcd,0, 0, 'C', temp);

Тогда можно будет вынести ф-цию в отдельный файл/модуль.



1



locm

15.09.2019, 21:07

Не по теме:

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

Arduino Uno.

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

AVR (Basic, немного Assembler).

Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.



0



Avazart

15.09.2019, 21:21

Не по теме:

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

Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.

Но лучше не надо …



0



Lavad

0 / 0 / 0

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

Сообщений: 25

16.09.2019, 12:12

13

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

это где ж такое написано?
функцию нужно объявить перед первым вызовом, сиречь сверху
можно и просто декларировать сверху
а объявить уже в удобном месте

Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции. А сама функция может располагаться по скетчу в ЛЮБОМ месте (но за пределами setup, loop и любых других функций). И больше никаких специфических строк.

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

вот так не надо делать(приравнивать функцию к нулю)…

Методом проб и ошибок уже понял :-).

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

или передавай символ… 'C'

Если передаю в одинарных кавычках

более одного

символа, а функция ждет как char str, то выводятся на экран только самый правый из отправленных символов. Отправил «абв», а выводится «в».
Выкрутился, прописав в функции char str[], а символы отправляю через двойные кавычки.

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

или проси передавать строку, например так… char * str

Буквально вчера попалось это в справочнике, но как-то не дошло, что тоже мой вариант :-).

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

Кроме того наверное лучше так:

C++
1
void myDispay(PCD8544& lcd,byte x, byte y, char str, float temp) {...}

Тогда можно будет вынести ф-цию в отдельный файл/модуль.

Благодарю за совет! Как-нибудь проверю…



0



Эксперт С++

8385 / 6147 / 615

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

Сообщений: 28,683

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

16.09.2019, 12:54

14

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

Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции

Нафиг выкиньте эти справочники.
Почитайте мои ссылки.



0



0 / 0 / 0

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

Сообщений: 25

16.09.2019, 13:00

15

Ссылки Ваши добавлены в закладки. Время от времени заглядываю.
Но теория для меня — всего лишь набор понятий. Я же высказался после практической проверки. А как я понял, так оно и работает :-)



0



Понравилась статья? Поделить с друзьями:
  • Error strlen was not declared in this scope
  • Error strings dat file not found
  • Error string or binary data would be truncated the statement has been terminated
  • Error string index out of range java
  • Error string in namespace std does not name a type