Ошибка c3861 printf идентификатор не найден

lethe1337

2 / 2 / 0

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

Сообщений: 177

1

18.05.2022, 22:12. Показов 1213. Ответов 4

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


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

В общем у меня есть задание: перенести программу с Си на С++. С плюсами знаком +- 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#include <atomic>
#include <stdio.h>
using namespace std;
 
class ClassList
{public:
    typedef struct Node
    {
        int key;
        struct Node* next;
        struct Node* prev;
    } Node;
 
    // вспомогательная сущность, хранящая указатель на начало списка и его размер
    typedef struct
    {
        size_t size;
        Node* head;
        Node* tail;
    } List;
 
    // получение адреса элемента по его порядковому номеру (счет от 1 )
    Node* Get_node(const List list, const int number)
    {
        int i;
        Node* scan = list.head;
 
        for (i = 1; i < number; i++)
            scan = scan->next;
 
        return scan;
    }
    Node* Create_node(const int key)
    {
        Node* new_node = (Node*)malloc(sizeof(Node));
        if (new_node)
        {
            new_node->key = key;
            new_node->next = NULL;
            return new_node;
            free(new_node);
        }
    }
    // вставка элемента в начало списка
    List Insert(List list, const int key)
    {
        Node* add = Create_node(key);
        if (list.head != NULL)
            add->next = list.head;
        list.head = add;
        list.size++;
 
        return list;
    }
 
    // вывод списка на экран
    void Print(const List list)
    {
        Node* scan = list.head;
        printf("List items: ");
        while (scan)
        {
            printf("%d -> %p ", scan->key, scan->next);
            scan = scan->next;
        }
    }
 
    // удаление элемента из начала ЛОС
    List Pop_front(List list)
    {
        Node* del = list.head;
        list.head = del->next;
        free(del);
        list.size--;
 
        return list;
    }
 
   
 
    // обмен местами двух элементов ЛОС
    void Swap(List list, Node* const before1, Node* const before2)
    {
        Node* self1, * self2, * tmp;
        // before1 = Get_node(list, N1-1);
        // before2 = Get_node(list, N2-1);
        self1 = before1->next;
        self2 = before2->next;
        tmp = before1->next;
        before1->next = before2->next;
 
        before2->next = tmp;
        tmp = self1->next;
        self1->next = self2->next;
        self2->next = tmp;
 
    }
 
    List Append(List list, const int num)
    {
        Node* const add_node = Create_node(num);
        list.size++;
 
        // если список пуст
        if (!list.head)
        {
            list.head = list.tail = add_node;
            return list;
        }
 
        list.tail->next = add_node;
        list.tail = add_node;
 
        return list;
    }
 
    int Get_Value(List list, int N)
    {
        Node* tmp = Get_node(list, N);
        return tmp->key;
    }
 
    void Inverse_sublist(const List list, const int K, const int N)
    {
        int i, j;
        Node* left = Get_node(list, K - 1);
        Node* right;
 
        for (i = 0; i < N / 2; i++)
        {
            right = left;
            for (j = 0; j < (N - 2 * i); j++)
                right = right->next;
 
            Swap(list, left, right);
            left = left->next;
        }
    }
};
 
//--------------------------------------------------------------
 
int main(int argc, char* argv[])
{
    logo();
    printf("В списке целых ненулевых элементов инвертировать K элементов начиная с Nn");
    srand((unsigned int)time(NULL));
    int i, tmpRand;
    int tmpHand[100]{};
    ClassList::Node* node_a = nullptr;
    ClassList::Node* node_b = nullptr;
 
    FILE* config;
    char Conf_Name[50] = "testo.cfg", buffer[100];
    int sposob = 0, elementov = 0, K = 0, N = 0;
if ((config = fopen(Conf_Name, "r")) == NULL) {
        puts("Config file error!!!");
        puts("Press Enter!!!");
        getchar(); exit(0);
    }
 
    fgets(buffer, 80, config);
    if (!strstr(buffer, "#!MYCONFIG")) {
        puts("Config file error!!!");
        puts("Press Enter!!!");
        getchar(); fclose(config);
        exit(0);
    }
 
    while (1)
    {
        fgets(buffer, 80, config);
        if (feof(config))break;
        if (buffer[0] == '#')continue;
        if (buffer[0] == '!') { puts(buffer); continue; }
        if (strstr(buffer, "sposob=")) {
            sposob = atoi(buffer + strlen("sposob="));
            continue;
        }
        if (strstr(buffer, "elementov=")) {
            elementov = atoi(buffer + strlen("elementov="));
            continue;
        }
        if (strstr(buffer, "K=")) {
            K = atoi(buffer + strlen("K="));
            continue;
        }
        if (strstr(buffer, "N=")) {
            N = atoi(buffer + strlen("N="));
            continue;
        }
 
    }
    puts("=============Result of parsing config file ========");
    printf("sposob = %dn", sposob);
    printf("elementov = %dn", elementov);
    printf("K = %dn", K);
    printf("N = %dn", N);
    puts("Press Enter!!!");
    getchar(); fclose(config);
 
 
    if (elementov > 20)
    {
        printf("Слишком много элементов в списке! Выход...n");
        return 1;
    }
    if (sposob != 1 && sposob != 2)
    {
        printf("Некорректный способ заполнения спискаn");
        return 1;
    }
    if (K + N > elementov)
    {
        printf("Некорректные данные в конфигурационном файле (N + K > элементовn)");
        return 1;
    }
    if (N > elementov)
    {
        printf("Некорректные данные: количество инвертируемых элементов больше чем элементов в спискеn");
        return 1;
    }
 
 
    // "объект" ЛОС с инициализацией
    ClassList::List list{};
    list.head = list.tail = NULL;
    list.size = 0;
 
    if (sposob == 2)
    {
        size_t t;
        for (i = 0; i < elementov; i++)
        {
            tmpRand = rand() % 100;
            list = Insert(list, tmpRand);
        }
        Print(list);
        Inverse_sublist(list, N, K);
        printf("nn");
        Print(list);
    }
    if (sposob == 1)
    {
        size_t t;
        for (int i = elementov; i > 0; i--)
        {
            printf("Введите элемент списка: n");
            scanf("%d", &tmpHand[i]);
            list = Append(list, tmpHand[i]);
        }
        Print(list);
        Inverse_sublist(list, N, K);
        printf("nn");
        Print(list);
    }
}

При компиляции выдает следующие ошибки:

Код

1>List.cpp
1>C:UsersFinsourcereposListListList.cpp(105,20): error C3861: Insert: идентификатор не найден
1>C:UsersFinsourcereposListListList.cpp(107,9): error C3861: Print: идентификатор не найден
1>C:UsersFinsourcereposListListList.cpp(108,9): error C3861: Inverse_sublist: идентификатор не найден
1>C:UsersFinsourcereposListListList.cpp(110,9): error C3861: Print: идентификатор не найден
1>C:UsersFinsourcereposListListList.cpp(119,20): error C3861: Append: идентификатор не найден
1>C:UsersFinsourcereposListListList.cpp(121,9): error C3861: Print: идентификатор не найден
1>C:UsersFinsourcereposListListList.cpp(122,9): error C3861: Inverse_sublist: идентификатор не найден
1>C:UsersFinsourcereposListListList.cpp(124,9): error C3861: Print: идентификатор не найден

Помогите исправить =)



0



zss

Модератор

Эксперт С++

13252 / 10391 / 6213

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

Сообщений: 27,793

19.05.2022, 09:07

2

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

Решение

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
238
239
240
241
242
243
244
245
246
247
248
249
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <ctime>
//#include <stdio.h>
using namespace std;
struct Node
{
    int key;
    struct Node* next;
    struct Node* prev;
};
struct List
{
    size_t size;
    Node* head;
    Node* tail;
};
 
 
// получение адреса элемента по его порядковому номеру (счет от 1 )
Node* Get_node(const List& list, int number)
{
    int i;
    Node* scan = list.head;
 
    for (i = 1; i < number; i++)
        scan = scan->next;
 
    return scan;
}
Node* Create_node(int key)
{
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->key = key;
    new_node->next = NULL;
    return new_node;
    //free(new_node);  ?????????????
}
// вставка элемента в начало списка
List Insert(List list, const int key)
{
    Node* add = Create_node(key);
    if (list.head != NULL)
        add->next = list.head;
    list.head = add;
    list.size++;
 
    return list;
}
 
// вывод списка на экран
void Print(const List list)
{
    Node* scan = list.head;
    printf("List items: ");
    while (scan)
    {
        printf("%d -> %p ", scan->key, scan->next);
        scan = scan->next;
    }
}
 
// удаление элемента из начала ЛОС
List Pop_front(List list)
{
    Node* del = list.head;
    list.head = del->next;
    free(del);
    list.size--;
 
    return list;
}
 
 
 
// обмен местами двух элементов ЛОС
void Swap(List list, Node* const before1, Node* const before2)
{
    Node* self1, * self2, * tmp;
    // before1 = Get_node(list, N1-1);
    // before2 = Get_node(list, N2-1);
    self1 = before1->next;
    self2 = before2->next;
    tmp = before1->next;
    before1->next = before2->next;
 
    before2->next = tmp;
    tmp = self1->next;
    self1->next = self2->next;
    self2->next = tmp;
 
}
 
List Append(List list, const int num)
{
    Node* const add_node = Create_node(num);
    list.size++;
 
    // если список пуст
    if (!list.head)
    {
        list.head = list.tail = add_node;
        return list;
    }
 
    list.tail->next = add_node;
    list.tail = add_node;
 
    return list;
}
 
int Get_Value(List list, int N)
{
    Node* tmp = Get_node(list, N);
    return tmp->key;
}
 
void Inverse_sublist(const List list, const int K, const int N)
{
    int i, j;
    Node* left = Get_node(list, K - 1);
    Node* right;
 
    for (i = 0; i < N / 2; i++)
    {
        right = left;
        for (j = 0; j < (N - 2 * i); j++)
            right = right->next;
 
        Swap(list, left, right);
        left = left->next;
    }
}
 
//--------------------------------------------------------------
 
int main(int argc, char* argv[])
{
    //logo();
    printf("В списке целых ненулевых элементов инвертировать K элементов начиная с Nn");
    srand((unsigned int)time(NULL));
    int i, tmpRand;
    int tmpHand[100]={};
    //ClassList::Node* node_a = 0;
    //ClassList::Node* node_b = 0;
 
    FILE* config;
    char Conf_Name[50] = "testo.cfg", buffer[100];
    int sposob = 0, elementov = 0, K = 0, N = 0;
    if ((config = fopen(Conf_Name, "r")) == NULL) {
        puts("Config file error!!!");
        puts("Press Enter!!!");
        getchar(); exit(0);
    }
 
    fgets(buffer, 80, config);
    if (!strstr(buffer, "#!MYCONFIG")) {
        puts("Config file error!!!");
        puts("Press Enter!!!");
        getchar(); fclose(config);
        exit(0);
    }
 
    while (true)
    {
        fgets(buffer, 80, config);
        if (feof(config))break;
        if (buffer[0] == '#')continue;
        if (buffer[0] == '!') { puts(buffer); continue; }
        if (strstr(buffer, "sposob=")) {
            sposob = atoi(buffer + strlen("sposob="));
            continue;
        }
        if (strstr(buffer, "elementov=")) {
            elementov = atoi(buffer + strlen("elementov="));
            continue;
        }
        if (strstr(buffer, "K=")) {
            K = atoi(buffer + strlen("K="));
            continue;
        }
        if (strstr(buffer, "N=")) {
            N = atoi(buffer + strlen("N="));
            continue;
        }
 
    }
    puts("=============Result of parsing config file ========");
    printf("sposob = %dn", sposob);
    printf("elementov = %dn", elementov);
    printf("K = %dn", K);
    printf("N = %dn", N);
    puts("Press Enter!!!");
    getchar(); fclose(config);
 
 
    if (elementov > 20)
    {
        printf("Слишком много элементов в списке! Выход...n");
        return 1;
    }
    if (sposob != 1 && sposob != 2)
    {
        printf("Некорректный способ заполнения спискаn");
        return 1;
    }
    if (K + N > elementov)
    {
        printf("Некорректные данные в конфигурационном файле (N + K > элементовn)");
        return 1;
    }
    if (N > elementov)
    {
        printf("Некорректные данные: количество инвертируемых элементов больше чем элементов в спискеn");
        return 1;
    }
 
 
    // "объект" ЛОС с инициализацией
    List list;
    list.head = list.tail = NULL;
    list.size = 0;
 
    if (sposob == 2)
    {
        for (i = 0; i < elementov; i++)
        {
            tmpRand = rand() % 100;
            list=Insert(list,tmpRand);
        }
        Print(list);
        Inverse_sublist(list, N, K);
        printf("nn");
        Print(list);
    }
    if (sposob == 1)
    {
        for (int i = elementov; i > 0; i--)
        {
            printf("Введите элемент списка: n");
            scanf("%d", &tmpHand[i]);
            list = Append(list, tmpHand[i]);
        }
        Print(list);
        Inverse_sublist(list, N, K);
        printf("nn");
        Print(list);
    }
}



1



2 / 2 / 0

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

Сообщений: 177

19.05.2022, 11:10

 [ТС]

3

zss, Вылезло это

Код

1>List.obj : error LNK2005: "struct List __cdecl Append(struct List,int)" (?Append@@YA?AUList@@U1@H@Z) уже определен в Class.obj
1>List.obj : error LNK2005: "struct Node * __cdecl Create_node(int)" (?Create_node@@YAPEAUNode@@H@Z) уже определен в Class.obj
1>List.obj : error LNK2005: "int __cdecl Get_Value(struct List,int)" (?Get_Value@@YAHUList@@H@Z) уже определен в Class.obj
1>List.obj : error LNK2005: "struct Node * __cdecl Get_node(struct List const &,int)" (?Get_node@@YAPEAUNode@@AEBUList@@H@Z) уже определен в Class.obj
1>List.obj : error LNK2005: "struct List __cdecl Insert(struct List,int)" (?Insert@@YA?AUList@@U1@H@Z) уже определен в Class.obj
1>List.obj : error LNK2005: "void __cdecl Inverse_sublist(struct List,int,int)" (?Inverse_sublist@@YAXUList@@HH@Z) уже определен в Class.obj
1>List.obj : error LNK2005: "struct List __cdecl Pop_front(struct List)" (?Pop_front@@YA?AUList@@U1@@Z) уже определен в Class.obj
1>List.obj : error LNK2005: "void __cdecl Print(struct List)" (?Print@@YAXUList@@@Z) уже определен в Class.obj
1>List.obj : error LNK2005: "void __cdecl Swap(struct List,struct Node * const,struct Node * const)" (?Swap@@YAXUList@@QEAUNode@@1@Z) уже определен в Class.obj
1>C:UsersFinsourcereposListx64DebugList.exe : fatal error LNK1169: обнаружен многократно определенный символ - один или более
1>Сборка проекта "List.vcxproj" завершена с ошибкой.
========== Сборка: успешно: 0, сбой: 1, в актуальном состоянии: 0, пропущено: 0==========

Добавлено через 4 минуты
Моя ошибка, у меня в папке с этим проектом был Class.cpp, в котором были написаны эти функции. Все работает!



0



lethe1337

2 / 2 / 0

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

Сообщений: 177

19.05.2022, 21:14

 [ТС]

4

zss, А можете объяснить, пожалуйста, в чем была ошибка?

Добавлено через 24 минуты
Оказалось, что это нужно реализовать через классы.
Header.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Funcs
{
    friend class Class;
 
public:
    struct Node* next;
    struct List;
    Node* Get_node(const List& list, int number);
    Node* Create_node(int key);
    // вставка элемента в начало списка
    List Insert(List list, const int key);
    // вывод списка на экран
    void Print(const List list);
    // удаление элемента из начала ЛОС
    List Pop_front(List list);
    // обмен местами двух элементов ЛОС
    void Swap(List list, Node* const before1, Node* const before2);
    List Append(List list, const int num);
    int Get_Value(List list, int N);
    void Inverse_sublist(const List list, const int K, const int N);
  
};

Header.cpp

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
#include "Header.h"
#include <atomic>
#include<stdio.h>
 
using namespace std;
 
class Class
{
    friend class Funcs;
 
public:
    struct Node
    {
        int key;
        struct Node* next;
        struct Node* prev;
    };
    struct List
    {
        size_t size;
        Node* head;
        Node* tail;
    };
    // получение адреса элемента по его порядковому номеру (счет от 1 )
    Node* Get_node(const List& list, int number)
    {
        int i;
        Node* scan = list.head;
 
        for (i = 1; i < number; i++)
            scan = scan->next;
 
        return scan;
    }
 
    Node* Create_node(int key)
    {
        Node* new_node = (Node*)malloc(sizeof(Node));
        new_node->key = key;
        new_node->next = NULL;
        return new_node;
        //free(new_node);  ?????????????
    }
    // вставка элемента в начало списка
    List Insert(List list, const int key)
    {
        Node* add = Create_node(key);
        if (list.head != NULL)
            add->next = list.head;
        list.head = add;
        list.size++;
 
        return list;
    }
 
    // вывод списка на экран
    void Print(const List list)
    {
        Node* scan = list.head;
        printf("List items: ");
        while (scan)
        {
            printf("%d -> %p ", scan->key, scan->next);
            scan = scan->next;
        }
    }
 
    // удаление элемента из начала ЛОС
    List Pop_front(List list)
    {
        Node* del = list.head;
        list.head = del->next;
        free(del);
        list.size--;
 
        return list;
    }
 
 
 
    // обмен местами двух элементов ЛОС
    void Swap(List list, Node* const before1, Node* const before2)
    {
        Node* self1, * self2, * tmp;
        // before1 = Get_node(list, N1-1);
        // before2 = Get_node(list, N2-1);
        self1 = before1->next;
        self2 = before2->next;
        tmp = before1->next;
        before1->next = before2->next;
 
        before2->next = tmp;
        tmp = self1->next;
        self1->next = self2->next;
        self2->next = tmp;
 
    }
 
    List Append(List list, const int num)
    {
        Node* const add_node = Create_node(num);
        list.size++;
 
        // если список пуст
        if (!list.head)
        {
            list.head = list.tail = add_node;
            return list;
        }
 
        list.tail->next = add_node;
        list.tail = add_node;
 
        return list;
    }
 
    int Get_Value(List list, int N)
    {
        Node* tmp = Get_node(list, N);
        return tmp->key;
    }
 
    void Inverse_sublist(const List list, const int K, const int N)
    {
        int i, j;
        Node* left = Get_node(list, K - 1);
        Node* right;
 
        for (i = 0; i < N / 2; i++)
        {
            right = left;
            for (j = 0; j < (N - 2 * i); j++)
                right = right->next;
 
            Swap(list, left, right);
            left = left->next;
        }
    }
};

в List.cpp код тот же, что и после main(), но при компиляции вылазят те же ошибки, что и в прошлый раз: идентификатор не найден. Как это можно исправить?



0



zss

Модератор

Эксперт С++

13252 / 10391 / 6213

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

Сообщений: 27,793

20.05.2022, 06:17

5

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

Решение

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

нужно реализовать через классы

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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <ctime>
//#include <stdio.h>
using namespace std;
struct Node
{
    int key;
    struct Node* next;
    struct Node* prev;
};
struct List
{
private:
    size_t size;
    Node* head;
    Node* tail;
public:
    List()
    {   
        head = tail = NULL;
        size = 0;
    }
// !!!! правило трех:
    ~List()
    {
        // Допишите удаление всего списка
    }
    List(const List& b)
    {
        // допишите копирование списка b в список *this
    }
    List& operator=(const List& b)
    {
        if(this!=&b)
        {
            // допишите копирование списка b в список *this
        }
        return *this;
    }
 
    Node* Get_node(int number);
    Node* Create_node(int key);
    void Insert(const int key);
    void Print();
    void Pop_front();
    void Swap(Node* const before1, Node* const before2);
    void Append(const int num);
    int Get_Value(int N);
    void Inverse_sublist(const int K, const int N);
};
 
 
// получение адреса элемента по его порядковому номеру (счет от 1 )
Node* List::Get_node(int number)
{
    int i;
    Node* scan = this->head;
 
    for (i = 1; i < number; i++)
        scan = scan->next;
 
    return scan;
}
Node* List::Create_node(int key)
{
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->key = key;
    new_node->next = NULL;
    return new_node;
}
// вставка элемента в начало списка
void List::Insert(const int key)
{
    Node* add = Create_node(key);
    if (this->head != NULL)
        add->next = this->head;
    this->head = add;
    this->size++;
}
 
// вывод списка на экран
void List::Print()
{
    Node* scan = this->head;
    printf("List items: ");
    while (scan)
    {
        printf("%d -> %p ", scan->key, scan->next);
        scan = scan->next;
    }
}
 
// удаление элемента из начала ЛОС
void List::Pop_front()
{
    Node* del = this->head;
    this->head = del->next;
    free(del);
    this->size--;
}
 
 
 
// обмен местами двух элементов ЛОС
void List::Swap(Node* const before1, Node* const before2)
{
    Node* self1, * self2, * tmp;
    // before1 = Get_node(list, N1-1);
    // before2 = Get_node(list, N2-1);
    self1 = before1->next;
    self2 = before2->next;
    tmp = before1->next;
    before1->next = before2->next;
 
    before2->next = tmp;
    tmp = self1->next;
    self1->next = self2->next;
    self2->next = tmp;
 
}
 
void List::Append(const int num)
{
    Node* const add_node = Create_node(num);
    this->size++;
 
    // если список пуст
    if (!this->head)
    {
        this->head = this->tail = add_node;
    }
 
    this->tail->next = add_node;
    this->tail = add_node;
}
 
int List::Get_Value(int N)
{
    Node* tmp = Get_node(N);
    return tmp->key;
}
 
void List::Inverse_sublist(const int K, const int N)
{
    int i, j;
    Node* left = Get_node(K - 1);
    Node* right;
 
    for (i = 0; i < N / 2; i++)
    {
        right = left;
        for (j = 0; j < (N - 2 * i); j++)
            right = right->next;
 
        Swap(left, right);
        left = left->next;
    }
}
 
//--------------------------------------------------------------
 
int main(int argc, char* argv[])
{
    //logo();
    printf("В списке целых ненулевых элементов инвертировать K элементов начиная с Nn");
    srand((unsigned int)time(NULL));
    int i, tmpRand;
    int tmpHand[100]={};
    //ClassList::Node* node_a = 0;
    //ClassList::Node* node_b = 0;
 
    FILE* config;
    char Conf_Name[50] = "testo.cfg", buffer[100];
    int sposob = 0, elementov = 0, K = 0, N = 0;
    if ((config = fopen(Conf_Name, "r")) == NULL) {
        puts("Config file error!!!");
        puts("Press Enter!!!");
        getchar(); exit(0);
    }
 
    fgets(buffer, 80, config);
    if (!strstr(buffer, "#!MYCONFIG")) {
        puts("Config file error!!!");
        puts("Press Enter!!!");
        getchar(); fclose(config);
        exit(0);
    }
 
    while (true)
    {
        fgets(buffer, 80, config);
        if (feof(config))break;
        if (buffer[0] == '#')continue;
        if (buffer[0] == '!') { puts(buffer); continue; }
        if (strstr(buffer, "sposob=")) {
            sposob = atoi(buffer + strlen("sposob="));
            continue;
        }
        if (strstr(buffer, "elementov=")) {
            elementov = atoi(buffer + strlen("elementov="));
            continue;
        }
        if (strstr(buffer, "K=")) {
            K = atoi(buffer + strlen("K="));
            continue;
        }
        if (strstr(buffer, "N=")) {
            N = atoi(buffer + strlen("N="));
            continue;
        }
 
    }
    puts("=============Result of parsing config file ========");
    printf("sposob = %dn", sposob);
    printf("elementov = %dn", elementov);
    printf("K = %dn", K);
    printf("N = %dn", N);
    puts("Press Enter!!!");
    getchar(); fclose(config);
 
 
    if (elementov > 20)
    {
        printf("Слишком много элементов в списке! Выход...n");
        return 1;
    }
    if (sposob != 1 && sposob != 2)
    {
        printf("Некорректный способ заполнения спискаn");
        return 1;
    }
    if (K + N > elementov)
    {
        printf("Некорректные данные в конфигурационном файле (N + K > элементовn)");
        return 1;
    }
    if (N > elementov)
    {
        printf("Некорректные данные: количество инвертируемых элементов больше чем элементов в спискеn");
        return 1;
    }
 
 
    // "объект" ЛОС с инициализацией
    List list;
    //list.head = list.tail = NULL;
    //list.size = 0;
 
    if (sposob == 2)
    {
        for (i = 0; i < elementov; i++)
        {
            tmpRand = rand() % 100;
            list.Insert(tmpRand);
        }
        list.Print();
        list.Inverse_sublist(N, K);
        printf("nn");
        list.Print();
    }
    if (sposob == 1)
    {
        for (int i = elementov; i > 0; i--)
        {
            printf("Введите элемент списка: n");
            scanf("%d", &tmpHand[i]);
            list.Append(tmpHand[i]);
        }
        list.Print();
        list.Inverse_sublist(N, K);
        printf("nn");
        list.Print();
    }
}

Я не проверял правильность методов.
Только перенес Ваш код в класс.
Обратите внимание на ненаписанные методы относящиеся к
ПРАВИЛУ ТРЕХ.
Если их не реализуете, то будут ошибки исполнения.



1



I have included stdio.h into my C++ project, why am I still getting this error? Also, after I added #include , printf(), in my code, was no longer underlined in red to suggest that there was any error.

Also, I would like to use the function, format(). Which library is that found in?

  • c++
  • printf
  • stdio

asked Apr 27, 2015 at 3:50

Raisintoe's user avatar

RaisintoeRaisintoe

2011 gold badge3 silver badges11 bronze badges

4

  • «Which library is that found in?» — Boost? TinyFormat? cppformat? You tell us.

    Apr 27, 2015 at 3:51

  • «I have included stdio.h into my C++ project, why am I still getting this error?» — please provide your compile command, your link command, and the exact error you are receiving. Do so by adding it to your question by clicking Edit (and don’t post it as a comment). Otherwise, there’s not enough information to help troubleshoot it.

    Apr 27, 2015 at 3:54

  • «I would like to use the function, format()…» — that’s not a standard C library function. What did you have in mind? Are you using an external library? Do you have a reference to the function?

    Apr 27, 2015 at 3:55

  • As with spelling in word processors, IDE underlining is just a hint that there could be something wrong. Underlining doesn’t definitely mean wrong, no underlining doesn’t definitely mean correct.

    Apr 27, 2015 at 4:54

2 Answers

you must include stdio.h instead of cstdio.h

#include <stdio.h>

answered Apr 27, 2015 at 4:14

Mohsen Bahaloo's user avatar

Use
#include< cstdio>
using namespace std;

after that you can use printf()

answered Apr 27, 2015 at 4:00

LoveToCode's user avatar

LoveToCodeLoveToCode

2962 silver badges18 bronze badges

1

  • Remove From My Forums
  • Question

  • I think I already know the answer to this but I’ll ask the question anyway.

    When I attempt to compile the following code:

    #include <stdio.h>

    #include <stdafx.h>

    int count;

    int main()

    {

    //Print the numbers 1 through 20

    for (count = 1; count <= 20; count++)

    printf(«%dn», count);

    return 0;

    }

    I get the message:  error C3861: ‘printf’: identifier not found

    Does this message have to do with the changes made to Visual C++?

    Am I missing something obvious? 

Answers

  • Try this:

    #include <stdafx.h>
    #include <stdio.h>

    Or turn off precompiled headers. The gory details of this problem is that on a /Yu build (that is a build that use a PCH) the compiler ignores anything before the header file that marks the end of the PCH region. We are in the process of adding a warning for this situation — this new warning will show up in the next release of Visual C++.

Использую библиотеку math.h и в ней для нахождения кубического корня есть функция cbrt();
Только вот при компиляции Visual Studio говорит: error C3861: cbrt: идентификатор не найден.

Мой код:

#include <stdio.h>
#include <cmath>

int main()
{
    double PI = 3.1415926535897932384626433832795, x=0.25, y=1.31, a=3.5, b=0.9, P;
    printf("Вы запустили программу для решения задачи 1 из лабораторной 1! n");
    printf("Программа начинает расчет, ожидайте... n");
    P=fabs((pow(sin(a*pow(x,3)+b*pow(y,2)-a*b),3))/(cbrt(pow((a*x*3+b*pow(y,2)-a),2)+PI)))+tan(a*pow(x,3)+b*pow(y,2)-a*b);
    printf("Ответ для Задачи 1: %d n", P);
    return 0;
}

Как решать проблему?

Я включил stdio.h в мой проект C ++, почему я все еще получаю эту ошибку? Кроме того, после того, как я добавил #include, printf () в моем коде больше не подчеркивался красным, чтобы предположить, что произошла какая-либо ошибка.

Также я бы хотел использовать функцию format (). В какой библиотеке это находится?

2

Решение

Вы должны включить stdio.h вместо cstdio.h

#include <stdio.h>

7

Другие решения

использование
#включают< cstdio>
использование пространства имен std;

после этого вы можете использовать printf ()

1

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка c3825 konica minolta
  • Ошибка c241301 kia rio
  • Ошибка c2215 мерседес glk
  • Ошибка c3300 kyocera 3501i

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

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