0 / 0 / 0
Регистрация: 24.02.2018
Сообщений: 23
1

Как передать Правильно в функцию тип char* ?

15.04.2018, 01:30. Показов 1448. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
ошибка происходит на 16 строчке кода в файле console application c++.cpp. Как ее исправить?
В программе есть 4 файла:
1 std_lib_facilities.h
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
/*
   std_lib_facilities.h
*/
 
/*
    simple "Programming: Principles and Practice using C++ (second edition)" course header to
    be used for the first few weeks.
    It provides the most common standard headers (in the global namespace)
    and minimal exception/error support.
 
    Students: please don't try to understand the details of headers just yet.
    All will be explained. This header is primarily used so that you don't have
    to understand every concept all at once.
 
    By Chapter 10, you don't need this file and after Chapter 21, you'll understand it
 
    Revised April 25, 2010: simple_error() added
    
    Revised November 25 2013: remove support for pre-C++11 compilers, use C++11: <chrono>
    Revised November 28 2013: add a few container algorithms
    Revised June 8 2014: added #ifndef to workaround Microsoft C++11 weakness
*/
 
#ifndef H112
#define H112 251113L
 
 
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
#include <conio.h>
 
//------------------------------------------------------------------------------
 
 
//------------------------------------------------------------------------------
 
typedef long Unicode;
 
//------------------------------------------------------------------------------
 
using namespace std;
 
 
//factorial
long double fact(int N)
{
    if (N < 0) // если пользователь ввел отрицательное число
        return 0; // возвращаем ноль
    else if (N == 0) // если пользователь ввел ноль,
        return 1; // возвращаем факториал от нуля - не удивляетесь, но это 1 =)
    else // Во всех остальных случаях
        return N * fact(N - 1); // делаем рекурсию. 
}
//
 
 
template<class T> string to_string(const T& t)
{
    ostringstream os;
    os << t;
    return os.str();
}
 
struct Range_error : out_of_range { // enhanced vector range error reporting
    int index;
    Range_error(int i) :out_of_range("Range error: "+to_string(i)), index(i) { }
};
 
 
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
    using size_type = typename std::vector<T>::size_type;
 
#ifdef _MSC_VER
    // microsoft doesn't yet support C++11 inheriting constructors
    Vector() { }
    explicit Vector(size_type n) :std::vector<T>(n) {}
    Vector(size_type n, const T& v) :std::vector<T>(n,v) {}
    template <class I>
    Vector(I first, I last) : std::vector<T>(first, last) {}
    Vector(initializer_list<T> list) : std::vector<T>(list) {}
#else
    using std::vector<T>::vector;   // inheriting constructor
#endif
 
    T& operator[](unsigned int i) // rather than return at(i);
    {
        if (i<0||this->size()<=i) throw Range_error(i);
        return std::vector<T>::operator[](i);
    }
    const T& operator[](unsigned int i) const
    {
        if (i<0||this->size()<=i) throw Range_error(i);
        return std::vector<T>::operator[](i);
    }
};
 
// disgusting macro hack to get a range checked vector:
#define vector Vector
 
// trivially range-checked string (no iterator checking):
struct String : std::string {
    using size_type = std::string::size_type;
//  using string::string;
 
    char& operator[](unsigned int i) // rather than return at(i);
    {
        if (i<0||size()<=i) throw Range_error(i);
        return std::string::operator[](i);
    }
 
    const char& operator[](unsigned int i) const
    {
        if (i<0||size()<=i) throw Range_error(i);
        return std::string::operator[](i);
    }
};
 
 
namespace std {
 
    template<> struct hash<String>
    {
        size_t operator()(const String& s) const
        {
            return hash<std::string>()(s);
        }
    };
 
} // of namespace std
 
 
struct Exit : runtime_error {
    Exit(): runtime_error("Exit") {}
};
 
// error() simply disguises throws:
inline void error(const string& s)
{
    throw runtime_error(s);
}
 
inline void error(const string& s, const string& s2)
{
    error(s+s2);
}
 
inline void error(const string& s, int i)
{
    ostringstream os;
    os << s <<": " << i;
    error(os.str());
}
 
 
template<class T> char* as_bytes(T& i)  // needed for binary I/O
{
    void* addr = &i;    // get the address of the first byte
                        // of memory used to store the object
    return static_cast<char*>(addr); // treat that memory as bytes
}
 
 
inline void keep_window_open()
{
    cin.clear();
    cout << "Please enter a character to exit\n";
    char ch;
    cin >> ch;
    return;
}
 
inline void keep_window_open(string s)
{
    if (s=="") return;
    cin.clear();
    cin.ignore(120,'\n');
    for (;;) {
        cout << "Please enter " << s << " to exit\n";
        string ss;
        while (cin >> ss && ss!=s)
            cout << "Please enter " << s << " to exit\n";
        return;
    }
}
 
 
 
// error function to be used (only) until error() is introduced in Chapter 5:
inline void simple_error(string s)  // write ``error: s and exit program
{
    cerr << "error: " << s << '\n';
    keep_window_open();     // for some Windows environments
    exit(1);
}
 
// make std::min() and std::max() accessible on systems with antisocial macros:
#undef min
#undef max
 
 
// run-time checked narrowing cast (type conversion). See ???.
template<class R, class A> R narrow_cast(const A& a)
{
    R r = R(a);
    if (A(r)!=a) error(string("info loss"));
    return r;
}
 
// random number generators. See 24.7.
 
 
 
inline int randint(int min, int max) { static default_random_engine ran; return uniform_int_distribution<>{min, max}(ran); }
 
inline int randint(int max) { return randint(0, max); }
 
//inline double sqrt(int x) { return sqrt(double(x)); } // to match C++0x
 
// container algorithms. See 21.9.
 
template<typename C>
using Value_type = typename C::value_type;
 
template<typename C>
using Iterator = typename C::iterator;
 
template<typename C>
    // requires Container<C>()
void sort(C& c)
{
    std::sort(c.begin(), c.end());
}
 
template<typename C, typename Pred>
// requires Container<C>() && Binary_Predicate<Value_type<C>>()
void sort(C& c, Pred p)
{
    std::sort(c.begin(), c.end(), p);
}
 
template<typename C, typename Val>
    // requires Container<C>() && Equality_comparable<C,Val>()
Iterator<C> find(C& c, Val v)
{
    return std::find(c.begin(), c.end(), v);
}
 
template<typename C, typename Pred>
// requires Container<C>() && Predicate<Pred,Value_type<C>>()
Iterator<C> find_if(C& c, Pred p)
{
    return std::find_if(c.begin(), c.end(), p);
}
 
#endif //H112
2 Account.h
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
#pragma once
 
namespace Program
{
    typedef unsigned int ui;
 
    class Account
    {
    private:
        char* ID;
        char* Name;
        ui Balance;
    public:
        Account();
        void    setID(char*);
        char*   getID();
 
        void    setName(char*);
        char*   getName();
 
        ui      getBalance();
        void    setBalance(ui);
        ~Account();
        
    };
 
}
3 Account.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
#include "Account.h"
 
namespace Program
{
 
    Account::Account()
    {
    }
 
    void Account::setID(char* id)
    {
        ID = id;
    }
 
    char * Account::getID()
    {
        return ID;
    }
 
    void Account::setName(char * name)
    {
        Name = name;
    }
 
    char * Account::getName()
    {
        return Name;
    }
 
 
    ui Account::getBalance()
    {
        return ui();
    }
 
    void Account::setBalance(ui b)
    {
        Balance = b;
    }
 
    Account::~Account()
    {
    }
}
4 console application c++.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Автор: Мурзин Алексей
//Class
 
#include <std_lib_facilities.h>
#include "Account.h"
 
using Program::Account;
 
int main()
{
    setlocale(LC_ALL, "Russian");
 
    Account a;
 
    a.setBalance(124);
    a.setID("№123");
    
    _getch();
    return 0;
}
Миниатюры
Как передать Правильно в функцию тип  char* ?  
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
15.04.2018, 01:30
Ответы с готовыми решениями:

Как в стандартную функцию WinAPI передать тип данных std::string вместо char*?
Помогите пожалуйста. Мне надо в GetDlgItemText передать std::string. Как это можно сделать?...

Как правильно передать в процедуру массив строк char*?
Нужно чтобы процедура возвращала измененный массив. Пытаюсь так: Void sss(char**arr) {...

Как передать в функцию char массив?
Стараюсь сделать консольную змейку. Вообще не понимаю ничего с этими char. #include &quot;stdafx.h&quot;...

Как правильно передать вектор в функцию и вызвать эту функцию?
Здравствуйте, объясните как исправить ошибку. Возникает после for(), выдается, что размер polygon =...

6
594 / 914 / 149
Регистрация: 10.08.2015
Сообщений: 4,775
15.04.2018, 02:37 2
strcpy(ID, id); это сработает, если выделить память для строк
1
Комп_Оратор)
Эксперт по математике/физике
8849 / 4591 / 619
Регистрация: 04.12.2011
Сообщений: 13,705
Записей в блоге: 16
15.04.2018, 09:38 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
#include <iostream>
#include <string>
using namespace std;
 
struct Const_char_owner{
//1
const char * const_s_str;
//2
static const size_t  n=32;//тут главное не поскупиться
char char_arr[n];
//3
string std_str;
Const_char_owner(const char * const_s_str_);
};
 
Const_char_owner::Const_char_owner(const char * const_s_str_)
:const_s_str(const_s_str_)
,std_str(const_s_str_)
{
if(strlen(const_s_str) < n)
strcpy(char_arr, const_s_str_);
else throw("ai-yai!");
}
 
int main(int argc, char* argv[])
{
Const_char_owner ccown("oops");
cout << ccown.const_s_str << ' ' << ccown.char_arr << ' ' << ccown.std_str << endl;
//вот в чём уязвимость массива с жестко заданной границей:
const char * more_32="mmmmmmmmmmmmmmoooooooooooooorrrrrrrrrrreeeeeeeeee_32";
cout<<"wow, the length is "<<strlen(more_32)<<" !!"<<endl;
try{
Const_char_owner dead_ccown(more_32);
}
catch(const char *ex){
cout<<ex<<endl;
}
//тут кроме опасности получить исключение есть и ещё неприятность: нужно использовать
//try catch чтобы его поймать, а этого нужно избегать любыми разумными средствами 
cout<<endl;
system("pause");
return 0;
}
использование класса string - самый беспроблемный, но и "дорогой".
0
82 / 78 / 34
Регистрация: 13.02.2018
Сообщений: 1,347
15.04.2018, 10:56 4
Цитата Сообщение от IGPIGP Посмотреть сообщение
но и "дорогой"
ну как сказать "дорогой", если строка имеет больше 28 букв, тогда char дорогой, string всегда будет занимать 28 байт, точнее, а char с каждым символом байт
0
0 / 0 / 0
Регистрация: 24.02.2018
Сообщений: 23
15.04.2018, 12:28  [ТС] 5
Цитата Сообщение от k0vpack Посмотреть сообщение
string всегда будет занимать 28 байт
Разве я не могу передать строку больше 28 байт, через тип string?
Цитата Сообщение от vlisp Посмотреть сообщение
strcpy(ID, id); это сработает, если выделить память для строк
Что делает эта штука? Как она работает? Где ее надо применять?
0
192 / 128 / 52
Регистрация: 19.01.2010
Сообщений: 518
15.04.2018, 12:56 6
Цитата Сообщение от k0vpack Посмотреть сообщение
string всегда будет занимать 28 байт
стринг это обертка, которая весит столько, но за собой она может тянуть строку-ресурс, который живет в куче и занимает уже памяти столько, сколько символов в строке. Так что получается суммарный объем строки будет больше на 28 байт, чем просто const char*. За исключением случая SSO-оптимизации
Цитата Сообщение от VibeProgramm Посмотреть сообщение
Разве я не могу передать строку больше 28 байт, через тип string?
можешь
Цитата Сообщение от VibeProgramm Посмотреть сообщение
Что делает эта штука? Как она работает? Где ее надо применять?
копирует все символы до терминирующего нуля из одного куска памяти в другой.
0
Комп_Оратор)
Эксперт по математике/физике
8849 / 4591 / 619
Регистрация: 04.12.2011
Сообщений: 13,705
Записей в блоге: 16
15.04.2018, 14:07 7
Цитата Сообщение от k0vpack Посмотреть сообщение
char с каждым символом байт
Тут не понял. Один байт - терминатор, - он один на всех. А вот бибилиотека string или cstring это таки деньги. Хотя я не видел случаев когда имело бы смысл экономить и не имело бы смысла перейти на чистый С. Предвижу холивар и спешу уверить, что участия не приму.
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
15.04.2018, 14:07
Помогаю со студенческими работами здесь

Как передать символ в функцию (const char *string)
Мне нужно передать в функцию atof символы F, F, S, S, но когда я пытаюсь так сделать ошибка invalid...

как правильно передать в качестве параметров указатель на тип QPainter ?
QPixmap *pix = new QPixmap(500,500); QPainter *pp = new QPainter(pix);...

Как правильно передавать char* в функцию?
Добрый всем! Есть две функции. Они должны выполнять одну и ту же вещь, только в одной хотел...

Как правильно передать функцию?
Как правильно передать функцию ? #include &quot;pch.h&quot; #include &lt;iostream&gt; using namespace std; ...

Как правильно передать id в функцию?
Добрый день всем! Есть задача: создать функцию-конструктор, которая создает круги. На вход она...

Как правильно передать параметр в функцию?
Есть вот такой код. В качестве примера пытаюсь вызвать метаметод layout() у наследника от QWidget...


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

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru