Ошибка e0020 идентификатор не определен

richlime

0 / 0 / 0

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

Сообщений: 16

1

02.12.2019, 19:00. Показов 19746. Ответов 2

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


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

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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#include <string.h>
#include <windows.h>
#include <conio.h>
#include <iostream>
#include <iomanip>
 
using namespace std;
 
class wow
{
    struct time
    {
        int day, mnt, year;
        string name;
        time* next;
    } *beg, * end;
public:
    wow() { beg = end = 0; };               // конструктор
    wow(const wow&);                // конструктор копирования
    ~wow();
    void addel();
    void show();
    void search();
    void delel();
};
 
wow::wow(const wow& temp) //конструктор копирования
{
    beg = new time;
    end = new time;
    if (!temp.beg) beg = end = 0;
    else
        if (!temp.beg->next)
        {
            beg->day = temp.beg->day;
            beg->mnt = temp.beg->mnt;
            beg->name = temp.beg->name;
            beg->year = temp.beg->year;
            beg->next = new time;
            beg->next = 0;
            end = beg;
        }
        else
        {
            beg->day = temp.beg->day;
            beg->mnt = temp.beg->mnt;
            beg->name = temp.beg->name;
            beg->year = temp.beg->year;
            time* tp = beg;
            time* tmp = temp.beg;
            tmp = tmp->next;
            while (tmp->next)
            {
                beg->next = new time;
                beg = beg->next;
                beg->day = tmp->day;
                beg->mnt = tmp->mnt;
                beg->name = tmp->name;
                beg->year = tmp->year;
                tmp = tmp->next;
 
            };
            beg->next = new time;
            beg = beg->next;
            beg->day = tmp->day;
            beg->mnt = tmp->mnt;
            beg->name = tmp->name;
            beg->year = tmp->year;
            beg->next = new time;
            beg->next = 0;
            end = beg;
            beg = tp;
        }
}
 
 
void wow::addel()       //добавление элемента
{
    system("cls");
    time* elem = new time;
    cin.clear(); cin.ignore(100, 'n');
    cout << " Введите название события: ";
    getline(cin, elem->name);
    cout << " Введите день, месяц и год: ";
    cin >> elem->day >> elem->mnt >> elem->year;
    if (beg == 0)
    {
        beg = new time;
        beg->day = elem->day;
        beg->mnt = elem->mnt;
        beg->year = elem->year;
        beg->name = elem->name;
        beg->next = 0;
        end = new time;
        end = beg;
 
    }
    else
    {
        end->next = new time;
        end = end->next;
        end->day = elem->day;
        end->mnt = elem->mnt;
        end->year = elem->year;
        end->name = elem->name;
        end->next = 0;
    }
}
 
void wow::delel()       //удаление элемента из очереди
{
    system("cls");
    if (!beg)
    {
        cout << " Очередь пуста. Что вы тут забыли? Нажмите что-нибудь...";
        cin.get();
    }
    else
        if (!beg->next)
        {
            cout << " Единственная запись удалена. Возрадуйтесь.";
            delete beg;
            delete end;
            cin.get();
        }
        else
        {
            cout << " Первая запись удалена. Воздрадуйтесь.";
            time* temp = beg;
            beg = beg->next;
            delete temp;
            cin.get();
        }
 
}
 
void wow::search()      //поиск элемента по дате
{
    system("cls");
    if (!beg)
    {
        cout << " Очередь пуста. Что вы тут забыли? Нажмите что-нибудь...";
        cin.get();
    }
    else
    {
        time* temp = beg;
        int year, month, day, fl = 0;
        cout << " Введите искомую дату через пробел" << endl;
        cin >> day >> month >> year;
        while (temp->next)
        {
            if ((temp->day == day) && (temp->mnt == month) && (temp->year == year))
            {
                cout << " Событие найдено! Это: " << temp->name << endl << " Нажмите что-то..." << endl;
                cin.get();
                fl = 1;
                break;
            }
            temp = temp->next;
        }
        delete temp;
        if (!fl) { cout << " Событие не найдено. Нажмите что-то" << endl; cin.get(); }
    }
}
 
 
void wow::show()    // вывод таблицы
{
    if (!beg) { cout << " Список пуст." << endl; }
    else
    {
        cout << "------------------------------------------------------------------------" << endl;
        cout << "|                 Название события                 | День | Месяц | Год |" << endl;
        time* temp = beg;
        while (temp)
        {
            cout << "|" << setw(50) << temp->name << "|" << setw(6) << temp->day << "|" << setw(7) << temp->mnt << "|" << setw(5) << temp->year << "|" << endl;
            temp = temp->next;
            if (!temp) break;
        }
        cout << "-------------------------------------------------------------------------" << endl;
    }
}
 
wow::~wow()
{
    time* temp = beg;
    if (beg) {
        while (beg->next) { beg = beg->next; delete temp; temp = beg; }
        delete end;
    }
}
wow perk;
void workingcopy(const wow)
{
    system("cls");
    wow perk3(perk);
    perk3.show();
    cin.get();
    cin.get();
}
 
 
 
int main()
{
    wow perk;
    wow perk2(perk);
    while (1)
    {
 
        system("cls");
        cout << " 1 - Добавление элемента в певую очередь" << endl;
        cout << " 2 - Добавление элемента во вторую очередь" << endl;
        cout << " 3 - Просмотр очереди" << endl;
        cout << " 4 - Поиск в первой очереди по дате" << endl;
        cout << " 5 - Поиск во второй очереди по дате" << endl;
        cout << " 6 - Удаление элемента из первой очереди" << endl;
        cout << " 7 - Удаление элемента из первой очереди" << endl;
        cout << " 8 - Демонстрация работы конструктора копирования" << endl;
        cout << " 9 - Выход" << endl;
        cout << " Ваш выбор: ";
        char i = cin.get();
        switch (i) {
        case '1': perk.addel(); break;
        case '2': perk2.addel(); break;
        case '3': {system("cls"); cout << " n Первая очередь:" << endl; perk.show();  cout << " Вторая очередь:" << endl; perk2.show();  cout << " Нажмите что-нибудь..." << endl; cin.get(); cin.get();break;}
        case '4': perk.search(); break;
        case '5': perk2.search(); break;
        case '6': perk.delel(); break;
        case '7': perk2.delel(); break;
        case '8': workingcopy(perk); break;
        case '9': return 0; break;
        }
    }
}

Подскажите, пожалуйста, выдает ошибку «E0020 идентификатор «getline» не определен» и «C3861 getline: идентификатор не найден». Что исправить надо? Строчка 83



0



Пишу программу на С++, в которой надо разработать определения двух классов COne и CTwo, которые связаны отношением включения.
Проблема возникает в protected класса CTwo (E0020 идентификатор "COne" не определен) и C3646 obj: неизвестный спецификатор переопределения. В чем может быть проблема?

//MAIN
#include <iostream>
#include <string>
#include "COne.h"
#include "CTwo.h"
int main()
{
    COne A("TEST ",1482);
    A.print();
    cout << A.getD() << endl;

    cout << A.getS() << endl;

}


//CONE.H
#ifndef CONE_H
#define CONE_H

#include <iostream>
#include <string>


using namespace std;

class COne
{

    protected:
        string s;
        double d;
        
    public:
        COne();
        COne(string S, double D);
        ~COne();

        COne(const COne& arg);
        
        void print();

        COne(COne& arg);

        const double& getD();
        const string& getS();

        void Print();

        COne& operator=(const COne& arg);

        friend class CTwo;
};
#endif

//CTWO.H
#ifndef CTWO_H
#define CTWO_H

#include <iostream>
#include <string>


using namespace std;

class CTwo
{
    protected:
        string s;
        COne obj;    // < -- - - ТУТ ОШИБКА

    public:
        CTwo(string S, string SOne, double d);



        friend class COne;
};

#endif

задан 21 окт 2021 в 7:42

Kartoshka98's user avatar

1

  1. Вам нужно подключать заголовки так, чтобы объявления оказались в нужной области видимости.
  2. Для избежания циклических включений (как в вашем случае) нужно использовать предварительное объявление.

Переделайте как то так:

CONE.H

#ifndef CONE_H
#define CONE_H

#include <iostream>
#include <string>
#include "CTwo.h"

using namespace std;

class COne
{

    protected:
        string s;
        double d;
        
    public:
        COne();
        COne(string S, double D);
        ~COne();

        COne(const COne& arg);
        
        void print();

        COne(COne& arg);

        const double& getD();
        const string& getS();

        void Print();

        COne& operator=(const COne& arg);

        friend class CTwo;
};
#endif

CTWO.H

#ifndef CTWO_H
#define CTWO_H

#include <iostream>
#include <string>


using namespace std;
class COne;

class CTwo
{
    protected:
        string s;
        COne obj;

    public:
        CTwo(string S, string SOne, double d);



        friend class COne;
};

#endif

ответ дан 21 окт 2021 в 7:48

Sheridan's user avatar

SheridanSheridan

3,10611 серебряных знаков31 бронзовый знак

4

morfeyka

0 / 0 / 0

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

Сообщений: 4

1

18.06.2019, 10:33. Показов 9670. Ответов 2

Метки base64, visual studio 2017, кодирование, visual studio (Все метки)


Пытался написать для алгоритма кодирования/декодирования base64 модуль для получения текста из файла и записи результатов в файл, но столкнулся с ошибками. В главном модуле (строка 37) ошибка e0020(идентификатор «с» не определен) и (строка 36) ошибка c2660 (функция не принимает 1 значение). Уже часа 3 сижу над проблемой, пока решал первую добавилась вторая, буду рад помощи.

Главный модуль

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
#include "pch.h"
#include "base64Head.h"
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
 
int main()
{
    setlocale(LC_ALL, ".1251");
    string a, k;
    try
    {
        cout << "Input file way" << endl;
        cin >> a;
        ifstream file(a, ios::binary);
        if (!file)
            throw 'f';
        cout << "Input save file way" << endl;
        cin >> k;
        ofstream file1(k, ios::binary);
        if (!file1)
            throw 'f';
        file.seekg(0, file.end);
        int l = file.tellg();
        file.seekg(0, file.beg);
        char* str = new char[l + 1];
        file.read(str, l);
        int vote;
        cout << "Inpute moden1.Coden2.Decode" << endl;
        cin >> vote;
        if (vote != 1 && vote != 2)
            throw 'm';
        if (vote == 1)
        {       
            string с = base64_encode(str, l);
            file1 << c;
        }
        if (vote == 2)
        {
            string c;
            c = base64_decode(str);
            file1 << c;
        }
    }
    //Обработка ошибок
    catch (char e)
    {
        switch (e)
        {
        case 'm':
        {
            cout << "Wrong mode" << endl;
            break;
        }
        case 'f':
        {
            cout << "Can't open file" << endl;
            break;
        }
        case 'i':
        {
            cout << "Wrong string" << endl;
            break;
        }
        }
    }
}

Заголовочный файл

C++
1
2
3
4
#include <string>
using namespace std;
string base64_encode(char*, int len);
string base64_decode(string const& s);

Дополнительный модуль

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
#include "pch.h" #include "base64Head.h" #include <iostream> using namespace std; // Использование 64 ьитного алфавита base64 static const string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Проверка вводимых значений static inline bool is_base64(unsigned char c) {     return (isalnum(c) || (c == '+') || (c == '/')); } // Кодирум наш текст string base64_encode(char* bytes_to_encode, int in_len) {     string ret;     int i = 0;     int j = 0;     char char_array_3[3];     char char_array_4[4];     // Запускаем цикл в котором выбираем по 3 байта и модифицируем их, как бы из 8 битного байта в 6 битный байт     while (in_len--) {         char_array_3[i++] = *(bytes_to_encode++);         if (i == 3) {             char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;             char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);             char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);             char_array_4[3] = char_array_3[2] & 0x3f;             // То что получилось запишем в переменную ret             for (i = 0; (i < 4); i++)                 ret += base64_chars[char_array_4[i]];             i = 0;         }     }     // Продолжаем, если отправили не пустое сообщение     if (i)     {         for (j = i; j < 3; j++)             // лобавляем в конце ноль, что бы сделать сишную строку             char_array_3[j] = '';         char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;         char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);         char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);         char_array_4[3] = char_array_3[2] & 0x3f;         for (j = 0; (j < i + 1); j++)             ret += base64_chars[char_array_4[j]];         // Если байтов меньше 3, то вместо них записывается знак "=", сколько отсутствует столько и "="         while ((i++ < 3))             ret += '=';     }     return ret; } string base64_decode(string const& encoded_string) {     int in_len = encoded_string.size();     int i = 0;     int j = 0;     int in_ = 0;     char char_array_4[4], char_array_3[3];     string ret;     // берем наш закодированную строку, идем обратном порядке и смотрим наличи пустых байтов     while (in_len - (encoded_string[in_]!= '=') && is_base64(encoded_string[in_])) {         char_array_4[i++] = encoded_string[in_]; in_++;         // аналогичные действия в обратном порядке         if (i == 4) {             for (i = 0; i < 4; i++)                 char_array_4[i] = base64_chars.find(char_array_4[i]);             char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);             char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);             char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];             for (i = 0; (i < 3); i++)                 ret += char_array_3[i];             i = 0;         }     }     if (i) {         for (j = i; j < 4; j++)             char_array_4[j] = 0;         for (j = 0; j < 4; j++)             char_array_4[j] = base64_chars.find(char_array_4[j]);         char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);         char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);         char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];         for (j = 0; (j < i - 1); j++) ret += char_array_3[j];     }     return ret; }

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

0

6574 / 4559 / 1843

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

Сообщений: 13,726

18.06.2019, 12:06

2

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

Решение

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

В главном модуле (строка 37) ошибка e0020(идентификатор «с» не определен)

У тебя одна из ‘с’ там русская

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

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

ошибка c2660 (функция не принимает 1 значение).

base64_encode(str.c_str(), l);

1

0 / 0 / 0

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

Сообщений: 4

18.06.2019, 14:13

 [ТС]

3

Спасибо за помощь, с русской раскладкой рил была ошибка, а вторую преобразование не решает, а добавляется еще одна «выражение должно иметь тип класса»(e0153)

Добавлено через 18 минут
я уже исправил вторую ошибку, там тоже дело было в опечатке)

0

IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

18.06.2019, 14:13

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

Полное кодирование файла в base64
Доброго, добрые форумчане, нужна помощь по кодированию текста, есть пять элементов текста и они…

кодирование отправляемых картинок в Base64
ну вот, научился я отправлять файлы с помощью WinInet.dll, текстовики улетают на ура, а вот…

Base64-кодирование файла перед отправкой формы
Добрый день, уважаемые программисты. Я очень мало понимаю в HTML и, к сожалению, ничего не понимаю…

Кодирование Base64 проблема с бинарным чтением файла
Есть следующий класс, где метод start() выполняет кодирование/декодирование Base64.
#pragma once…

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

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

3

Error E0020, error code description not found on google!

Why when i literally copy paste some code, there is always so many errors??? I checked semantics and everything is correct. I will link my source code and source i got it from… Btw c++ is backwards compatible right? Or it would compile using older ISO standard no? So i don’t think that’s it. And i am using VS community 19, so not having newest standard is not problem either.

Following is source code in my program:

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
#include <iostream> #include <conio.h> using namespace std; int main() { char key; int asciiValue; cout << "press a key to check its ascii valuenPress ESC to exitn" << endl; While(1) { key = getch(); asciiValue = key; if (asciiValue == 27) break; cout << "" } return 0; } 

This is source when i got source code from: https://www.youtube.com/watch?v=6-vlLvBnIR0

I tried to google: c++ error code E0020, with description from VS: identifier «while» is undefined. And google literally didn’t find any result. So whole search would be like: c++ error code E0020 «identifier «while» is undefined»
And nothing was found… Wait what??? How does something basic like that not even finds?

while, lower case, not While with an upper case w.

Too many youtube coding videos are garbage.

While I agree, the capital W is not the youtube channel’s fault. It’s lowercase in both the video and the pastebin link.

Compiler error message give line numbers to point to where the error is, so next time you run into something like this, look around the line number it tells you to spot typos.

Anywho, C++ is case-sensitive, so be aware of that.

Btw c++ is backwards compatible right?

With its previous standards? Not completely; there are some features deprecated or features that have become more strict as of C++11 and beyond. But as a beginner you shouldn’t need to worry much about that.

Last edited on

This isn’t standard c++ anyway. conio.h is a windows extension.

But you clearly DIDN’T copy-paste the code, or it wouldn’t have suffered an uppercase/lowercase malfunction.

Hmm i could swear i saw big W, i can’t explain it now as i look on the video. But i don’t think that’s it usually. Than probably it was incorrect code many times. I couldn’t paste code from video. I should say, i written it myself according to the video. But i double checked it, before post.

Yeah i know about line number, which shows where is the error, it usually doesn’t help me. I try to find error in a context of code, but i don’t find anything in 99% of cases. I know it is case sensitive. I really don’t know why i wrote large W in this case and i don’t think semantics are usually the problem.

And because it is not completely backwards compatible as Ganado say i guess. Or some extension…

Anyway, i really don’t know why even description doesn’t find any results on google. And usually: even if i try include context with it and error code…

It is so annoying, i am trying to create simple c++ program, which detects a keypress and googling keeps finding solutions, which using extensions, or deprecated functions. Should i create new post, or ask in this for help ? I am reading rules, but i don’t even know, if this forums is meant for posting questions: about how to make a program…

Last edited on

c++ is only somewhat portable and backwards compatible, even if you ignore all libraries outside the language (eg, cstdlib is ok but conio isnt). Really old code that may have depended on integers being 32 bit or 16 bit instead of 64, for example, could be unfixable to get working today — all it takes is one line that assumes the size of a type that has since changed and it can break badly.

These issues can be addressed now, with precisely named types (eg int64_t) but back when, those did not exist and the coder just did what made sense.

this is just a gap in the language. Keypress isnt easy to do in c++ without operating system extensions, because of how the I/O part is handled at both ends (both by the c++ compiler/language and by the OS/hardware). Its doable, but its not simple at all, and many a coder has found this to be an aggravation. Just use the extension for your compiler/os, and if its portable, code it for each and put a compiler flag around it to use the right one for the target.

For windows specifically, getch is an option but visual studio lets you pull in keypress as well, which is a little more powerful and smart. Either one is the way to go. If you can’t get getch working, … there should be a way to help you through that, post new errors after you fix the while etc.

Yes, ask here for help. There should be some examples of both getch and keypress in these forums as well, if you search old posts. When asking here, post your code, what you want to do, and what is wrong with your own code if any (error messages? bug info eg I put in x, I get y, and I wanted z)

Last edited on

Adapted macOS Catalina version

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
#include <iostream> //#include <cstdio> int main() { // Set terminal to raw mode system("stty raw"); // Loop for single character, 'q' to quit char input{0}; while ( std::cout << "Press any key to continue ... " and (input = getchar()) and input != 'q' ) { std::cout << " You pressed --" << input << "--n"; } // Reset terminal to normal "cooked" mode system("stty cooked"); // And we're out of here std::cout << "nThankyou and bye!!n"; return 0; }

Topic archived. No new replies allowed.

I realy don’t know what i need to do to fix this. Iam using Visual. Precompilied headers off, sdl check off. Task is «Find the vertices of the graph that are in the back distance from the vertex»

Main file:

#include "Header.h" int main() { int start, length, number; char file1[] = "data.txt"; char file2[] = "result.txt"; queue **graph = NULL; input(&number, &start, &length, &graph, file1); queue *buffer = new queue({ NULL, NULL }); search(&number, &start, &length, &graph, &buffer); output(&buffer, file2, start, length); system("PAUSE"); } 

Header.h:

#include <stdio.h> #include <windows.h> #include "vertex.h" //ввод void input(int *number, int *start, int *lenght, queue ***graph, char file[]) { int v1, v2; char c; FILE* in = fopen(file, "r"); if (in) { fscanf(in, "%d %d %dn", number, start, lenght); //считывается количество вершин, начальная вершина, длина пути и определяется ориентированный ли граф *graph = new queue*[*number]; //область, куда будет записываться список смежности for (int i = 0; i < *number; i++) (*graph)[i] = new queue({ NULL, NULL }); for (int i = 0; i < *number; i++) //ввод списка смежности { fscanf(in, "%d", &v2); //считывание строки fscanf(in, "%c", &c); //проверка есть ли элементы while (c != 'n') { if (fscanf(in, "%d", &v1)) //считывание граничащих вершин { push((*graph)[v2], v1); push((*graph)[v1], v2); } fscanf(in, "%c", &c); //проверка есть ли еще элементы } } fclose(in); } } //вывод void output(queue **buffer, char text[], int start, int length) { FILE *out = fopen(text, "w"); if (!(*buffer)->begin) { fprintf(out, "От вершины %d нет вершин на пути длинной %d", start, length); return; } while ((*buffer)->begin) //выводятся все элементы очереди { int a; pop(*buffer, a); fprintf(out, "%d ", a); } fclose(out); } void step(int* numE, int* numO, bool** odd, queue ***graph, queue** qu) { while (*numE > 0) //Элементы будут добавляться пока не пройдут все { //элементы добавленные на прошлом шагу int n; pop(*qu, n); //Элемент из очереди vertex* d = (*graph)[n]->begin; //Обход граничащих с n элементов while (d != NULL) //Пока не пройдут все граничущие элементы { if (!(*odd)[d->value]) { push(*qu, d->value); //В очередь граничащего элемен-та (*odd)[d->value] = true; //ставим флажок добавленный элемент (*numO)++; } d = d->next; //Переход к следующему граничащему элементу } (*numE)--; } } //поиск вершин у связного графа void search(int *number, int *start, int *length, queue ***graph, queue **comp) { bool* even = new bool[*number]; //Массив для хранения вершин на четном ходу bool* odd = new bool[*number]; //Массив для хранения вершин на нечетном ходу bool flag = false; //Флажок на проверку изолированную вершину int numO = 1, numE = 0; //Количество добавленных элементов во время прошлого хода queue* qu = new queue({ NULL, NULL });// записываются новые элементы for (int i = 0; i < *number; i++) //Обнуление массивов { odd[i] = 0; even[i] = 0; } push(qu, *start); //Добавление стартового элемента odd[*start] = true; for (int j = 0; j < *length; j++) { if (j % 2) { if (!numE) break; step(&numE, &numO, &odd, graph, &qu); } else { if (!numO) break; step(&numO, &numE, &even, graph, &qu); if (!flag && numE) //если было добавление, то убираем флажок flag = true; } } if (*length % 2) { for (int i = 0; i < *number; i++) if (even[i]) push(*comp, i); } else if (flag || *length == 0) for (int i = 0; i < *number; i++) if (odd[i]) push(*comp, i); } 

vertex.h:

struct vertex { int value; vertex *next; }; struct queue { vertex *begin; vertex *end; }; void input(int *number, int *start, int *lenght, queue ***graph, char file[]); void output(queue **buffer, char text[], int start, int length); void step(int* numE, int* numO, bool** odd, queue ***graph, queue** qu); void search(int *number, int *start, int *length, queue ***graph, queue **comp); 

E0020 identifier «pop» is undefined
E0020 identifier «push» is undefined
C3861 ‘push’: identifier not found
C3861 ‘pop’: identifier not found

Я пытаюсь отправить два массива в функцию с помощью указателей.

Затем я пытаюсь присвоить разыменованные значения из двух *массивов (отправляемых в качестве аргументов при вызове функции) двум массивам (не указателям), где ими можно манипулировать с большей легкостью.

Примечание: нет объектов или классов. Я не вижу никакого рессона для динамической обработки памяти (создать, удалить).

Исходные массивы в main:

int arr_fractions[2][7]
{
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
int arr_converted_values[2][7]
{
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};

Это вызов функции, в основном:

arr_converted_values[2][7] = decimal_conversion(arr_decimals, *arr_converted_values, &var_fract_length);

Функция:

int decimal_conversion(long double* arr_temp_decimals, int* arr_converted_values, int* var_fract_length)
{
// pointer retrieval ----------------------------------------------------------------
long double arr_temp_decimals[2][7]
{
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
int arr_temp_values[2][7]
{
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};
int var_tempt_fract_value = *var_fract_length;
for (int* var_temp_storage = 0; *var_temp_storage < *var_fract_length; *var_temp_storage++)
{
arr_temp_decimals[0][*var_temp_storage] = &arr_decimals[0][*var_temp_storage];
arr_temp_decimals[1][*var_temp_storage] = &arr_decimals[1][*var_temp_storage];
arr_temp_values[0][*var_temp_storage] = arr_converted_values[0][var_temp_storage];
arr_temp_values[1][*var_temp_storage] = arr_converted_values[1][var_temp_storage];
}
// --------------------------------------------------------------------------------------------
...
...
...
return (*arr_converted_values);
}

Три ошибки (ниже), которые я получаю, указывают на использование массива в цикле for, показанном выше.

E0142: выражение должно иметь тип указателя на объект, но имеет тип —>arr_*temp_*decinmals[0[*var_temp_storage]

E0142: выражение должно иметь тип указателя на объект, но имеет тип —>arr_*temp_*decinmals[1]*var_temp_storage]

E0020: идентификатор «arr_decimals» не определен — > &arr_decinmals[0][*var_temp_storage];

2 ответа

Проблема в том, что вы пытаетесь присвоить значение массиву, что невозможно. Массивы не могут быть назначены в C++

Возможно, вы захотите присвоить значение элементу массива, например:

arr_temp_decimals[0][*var_temp_storage] = arr_decimals[0][*var_temp_storage];

Однако и это не сработает, потому что вы пытаетесь присвоить значение типа long double элементу типа int. Сначала вам нужно будет преобразовать значение, например:

arr_temp_decimals[0][*var_temp_storage] = static_cast<int>(arr_decimals[0][*var_temp_storage]);

В качестве альтернативы вы можете изменить тип массива arr_temp_decimals на тип long double, например:

long double arr_temp_decimals[2][7]
{
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
};


0

Igor
17 Ноя 2022 в 06:38

В вашем фрагменте много ошибок.

arr_temp_decimals имеет переопределение in int decimal_conversion()

идентификатор «arr_decimals» не определен

Вы не объявляли arr_decimals раньше в функции.

Arr_decimals помещается в decimal_conversion(arr_decimals…). Так что это будет

 arr_decimals[0][*var_temp_storage] = arr_decimals[0][*var_temp_storage];

Arr_converted_values ​​— статический двумерный массив. Попробуйте изменить параметр функции int* arr_converted_values на int arr_converted_values[][7].

for (int* var_temp_storage = 0; *var_temp_storage < *var_fract_length; *var_temp_storage++)
arr_converted_values[0][var_temp_storage];

Адрес указателя нельзя использовать как arr_converted_values[0][var_temp_storage].

Рассмотрите возможность использования std::vector .


0

Minxin Yu — MSFT
18 Ноя 2022 в 12:04

  • Remove From My Forums
  • Вопрос

  • Только начал обучение С++ по учебнику Страуструпа.
    Загрузил Visual Studio

    Начал со стандартного «Hello, World!» 

    Отладка проходит успешно, ошибок нет.

    Однако программа не запускается. 

    Выходят следующие сообщения:

    Следующий проект устарел: Hello, World — Debug Win32

    Не удается запустить программу: …/HelloWorld.exe
    Не удается найти указанный файл

    Что я делаю не так?

    Система: Wind x64.

Ответы

  • Книга нашего дорогого и горячо любимого Страуструпа написана о языке программирования, а не о работе в среде разработки Visual Studio. Последнее описано в справочной системе (в крайнем случае, есть сайт msdn.microsoft.com/library).
    Советую там ознакомиться с технологией создания проекта VC++ и процедурой преобразования исходного кода в исполняемый модуль.

    • Изменено

      20 ноября 2013 г. 5:37

    • Помечено в качестве ответа
      Maksim MarinovMicrosoft contingent staff, Moderator
      2 декабря 2013 г. 7:42

I realy don’t know what i need to do to fix this. Iam using Visual. Precompilied headers off, sdl check off. Task is «Find the vertices of the graph that are in the back distance from the vertex»

Main file:

#include "Header.h"
int main()
{
    int start, length, number;
    char file1[] = "data.txt";
    char file2[] = "result.txt";
    queue **graph = NULL;
    input(&number, &start, &length, &graph, file1);
    queue *buffer = new queue({ NULL, NULL });
    search(&number, &start, &length, &graph, &buffer);
    output(&buffer, file2, start, length);
    system("PAUSE");
}

Header.h:

#include <stdio.h>
#include <windows.h>
#include "vertex.h"

//ввод
void input(int *number, int *start, int *lenght, queue ***graph, char file[])
{
    int v1, v2;
    char c;
    FILE*  in = fopen(file, "r");
    if (in)
    {
        fscanf(in, "%d %d %dn", number, start, lenght); //считывается количество вершин, начальная вершина, длина пути и определяется ориентированный ли граф
        *graph = new queue*[*number];   //область, куда будет записываться список смежности 
        for (int i = 0; i < *number; i++)
            (*graph)[i] = new queue({ NULL, NULL });

        for (int i = 0; i < *number; i++)       //ввод списка смежности
        {
            fscanf(in, "%d", &v2);  //считывание строки
            fscanf(in, "%c", &c);   //проверка есть ли элементы

            while (c != 'n')
            {
                if (fscanf(in, "%d", &v1)) //считывание граничащих вершин
                {
                    push((*graph)[v2], v1);
                    push((*graph)[v1], v2);
                }
                fscanf(in, "%c", &c);   //проверка есть ли еще элементы
            }
        }
        fclose(in);
    }
}

//вывод
void output(queue **buffer, char text[], int start, int length)
{
    FILE *out = fopen(text, "w");
    if (!(*buffer)->begin)
    {
        fprintf(out, "От вершины %d нет вершин на пути длинной %d", start, length);
        return;
    }
    while ((*buffer)->begin)            //выводятся все элементы очереди
    {
        int a;
        pop(*buffer, a);
        fprintf(out, "%d ", a);
    }
    fclose(out);
}

void step(int* numE, int* numO, bool** odd, queue ***graph, queue** qu)
{
    while (*numE > 0)       //Элементы будут добавляться пока не пройдут все
    {               //элементы добавленные на прошлом шагу
        int n;
        pop(*qu, n);            //Элемент из очереди
        vertex* d = (*graph)[n]->begin; //Обход граничащих с n элементов
        while (d != NULL)       //Пока не пройдут все граничущие элементы
        {
            if (!(*odd)[d->value])
            {
                push(*qu, d->value);        //В очередь граничащего элемен-та
                (*odd)[d->value] = true;    //ставим флажок добавленный элемент     
                (*numO)++;
            }
            d = d->next;        //Переход к следующему граничащему элементу
        }
        (*numE)--;
    }

}

//поиск вершин у связного графа
void search(int *number, int *start, int *length, queue ***graph, queue **comp)
{
    bool* even = new bool[*number];     //Массив для хранения вершин на четном ходу
    bool* odd = new bool[*number];  //Массив для хранения вершин на нечетном ходу 
    bool flag = false;          //Флажок на проверку изолированную вершину
    int numO = 1, numE = 0;     //Количество добавленных элементов во время прошлого хода
    queue* qu = new queue({ NULL, NULL });// записываются новые элементы
    for (int i = 0; i < *number; i++)   //Обнуление массивов
    {
        odd[i] = 0;
        even[i] = 0;
    }
    push(qu, *start);           //Добавление стартового элемента
    odd[*start] = true;
    for (int j = 0; j < *length; j++)
    {
        if (j % 2)
        {
            if (!numE)  break;
            step(&numE, &numO, &odd, graph, &qu);
        }
        else
        {
            if (!numO)
                break;
            step(&numO, &numE, &even, graph, &qu);
            if (!flag && numE)      //если было добавление, то убираем флажок 
                flag = true;
        }

    }
    if (*length % 2)
    {
        for (int i = 0; i < *number; i++)
            if (even[i])
                push(*comp, i);
    }
    else
        if (flag || *length == 0)
            for (int i = 0; i < *number; i++)
                if (odd[i])
                    push(*comp, i);

}

vertex.h:

struct vertex
{
    int value; vertex *next;
};

struct queue
{
    vertex *begin; vertex *end;
};

void input(int *number, int *start, int *lenght, queue ***graph, char file[]);
void output(queue **buffer, char text[], int start, int length);
void step(int* numE, int* numO, bool** odd, queue ***graph, queue** qu);
void search(int *number, int *start, int *length, queue ***graph, queue **comp);

E0020 identifier «pop» is undefined
E0020 identifier «push» is undefined
C3861 ‘push’: identifier not found
C3861 ‘pop’: identifier not found

По заданию необходимо сделать простенький тест, по завершении которого отображается количество полученных в ходе теста баллов. Использую VS2019, проект CLR (.NET Framework)
Я хотел прописать вычисление баллов в свойствах кнопки «Завершить», однако я плохо знаю регистр С++ в Windows.Forms, из примеров было только нечто подобное на C#.

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
	int bal = 0;
	if (radioButton4_CheckedChanged) bal = bal + 1;
	if (radioButton6_CheckedChanged) bal = bal + 1;
	if (radioButton10_CheckedChanged) bal = bal + 1;
	if (radioButton14_CheckedChanged) bal = bal + 1;
	if (radioButton19_CheckedChanged) bal = bal + 1;
	if (checkBox1_CheckedChanged && checkBox2_CheckenChanged) bal = bal + 1;
	if (checkBox5_CheckedChanged && checkBox7_CheckenChanged) bal = bal + 1;
	if (checkBox9_CheckedChanged && checkBox10_CheckenChanged) bal = bal + 1;
	if (checkBox15_CheckedChanged && checkBox4_CheckenChanged) bal = bal + 1;
}

Первые введенные radioButton и checkBox имеют ошибку :
«E2071 — Указатель на элемент недопустим для класса управляемый.»
Все последующие radioButton и checkBox не определены:
«E0020 — идентификатор «radioButton6_CheckedChanged» не определен».
И, если можно, подскажите, как вывести балл в label. Видел на C# команду label.Text = «…», но на С++ даже что-то похожее не нашел, хотя те же команды для чекбоксов и радиобаттонов практически идентичны, только вместо точки ставится нижнее подчеркивание.

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

  • Ошибка e01 на котле baxi luna 3
  • Ошибка e002 kugoo m4 pro
  • Ошибка e01 на котле baltgaz
  • Ошибка e0017 kyocera fs 1020mfp
  • Ошибка e01 на газовом котле термона

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

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