Ошибка e0020 visual studio

morfeyka

0 / 0 / 0

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

Сообщений: 4

1

18.06.2019, 10:33. Показов 10621. Ответов 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



6577 / 4562 / 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.

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

The solution is
Gets replaced with gets_s

Gets function has a buffer overflow vulnerability, and the program using the GETS function has the risk of buffer overflow
If you read the STR is a carefully constructed string, it will cause a buffer overflow and cause the program process to change.
gets () function
1. Description
The C library function Char *Gets (Char *STR) enters Stdin from the standard and stores it in the string pointed by the STR. When you read the royal symbol or reach the end of the file, it stops, depending on the situation.

GETS (STR) is equal to scanf («%s», & str) to write the read string to the array, but it is different.
2. Different
Scanf («%S», & Str): Stop it when you read the space.
gets (STR): Read until you knock on the car (whether there is a space in the middle).

(Difference 2)
By the way, the difference between printf () and puts ()

Puts () will automatically convert the ‘ 0’ to ‘ n’ when the output string is output, that is, the PUTS method will be automatically changed after the string is output.

#include <stdio.h>

int main(void) {
	char str[20];
	char str2[20];
	gets(str);
	scanf("%s", str2);
	puts(str);//==printf("%sn", &str);
	printf("%s", str2);
}
  • Remove From My Forums
  • Question

  • Whenever i use #Include «wincodec.h» i get alot of errors. These errors consist of:

    Severity	Code	Description	Project	File	Line	Suppression State
    Error	C2061	syntax error: identifier 'DXGI_JPEG_QUANTIZATION_TABLE'	Project20	c:program files (x86)windows kits10include10.0.17763.0umwincodec.h	8170	
    
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error	C2061	syntax error: identifier 'DXGI_JPEG_QUANTIZATION_TABLE'	Project20	c:program files (x86)windows kits10include10.0.17763.0umwincodec.h	8359	
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error	C2061	syntax error: identifier 'DXGI_JPEG_DC_HUFFMAN_TABLE'	Project20	c:program files (x86)windows kits10include10.0.17763.0umwincodec.h	8165	
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error	C2061	syntax error: identifier 'DXGI_JPEG_DC_HUFFMAN_TABLE'	Project20	c:program files (x86)windows kits10include10.0.17763.0umwincodec.h	8354	
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error	C2061	syntax error: identifier 'DXGI_JPEG_AC_HUFFMAN_TABLE'	Project20	c:program files (x86)windows kits10include10.0.17763.0umwincodec.h	8160	
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error	C2061	syntax error: identifier 'DXGI_JPEG_AC_HUFFMAN_TABLE'	Project20	c:program files (x86)windows kits10include10.0.17763.0umwincodec.h	8349	
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error (active)	E0020	identifier "DXGI_JPEG_QUANTIZATION_TABLE" is undefined	Project20	c:Program Files (x86)Windows Kits10Include10.0.17763.0umwincodec.h	8170	
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error (active)	E0020	identifier "DXGI_JPEG_QUANTIZATION_TABLE" is undefined	Project20	c:Program Files (x86)Windows Kits10Include10.0.17763.0umwincodec.h	8359
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error (active)	E0020	identifier "DXGI_JPEG_DC_HUFFMAN_TABLE" is undefined	Project20	c:Program Files (x86)Windows Kits10Include10.0.17763.0umwincodec.h	8165	
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error (active)	E0020	identifier "DXGI_JPEG_DC_HUFFMAN_TABLE" is undefined	Project20	c:Program Files (x86)Windows Kits10Include10.0.17763.0umwincodec.h	8354	
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error (active)	E0020	identifier "DXGI_JPEG_AC_HUFFMAN_TABLE" is undefined	Project20	c:Program Files (x86)Windows Kits10Include10.0.17763.0umwincodec.h	8160	
    
    Severity	Code	Description	Project	File	Line	Suppression State
    Error (active)	E0020	identifier "DXGI_JPEG_AC_HUFFMAN_TABLE" is undefined	Project20	c:Program Files (x86)Windows Kits10Include10.0.17763.0umwincodec.h	8349	
    
    
    
    
    
    

Понравилась статья? Поделить с друзьями:
  • Ошибка e002 whatsminer m20s
  • Ошибка e02 мультиварка редмонд
  • Ошибка e002 kugoo m4 pro
  • Ошибка e02 китайская автономка
  • Ошибка e0017 kyocera fs 1020mfp