why I am I getting this error?
*EDIT I posted my solution at the bottom. It turns out that I wasn’t able to use strcpy() in a particular section of my program.
asked May 1, 2012 at 22:13
user1066524user1066524
3432 gold badges11 silver badges23 bronze badges
0
Do you mean strcpy()
? There is no standard function called strcopy()
that I know of. Also, if you are using C++, then if possible, use std::string
instead since this will handle copying and other string manipulation for you.
answered May 1, 2012 at 22:14
dreamlaxdreamlax
93.1k29 gold badges162 silver badges209 bronze badges
7
I figured out a solution that worked for me. if you are having issues like I did with strcpy, you can use size() to figure out the size of the string and then use a while loop to go through and add it to the char array. this is what eventually worked for me :
let’s say we have a data structure member with a char array data.name[30] and we have two words in the file that make up the name (first and last) and we can’t just add it to the char array with strcpy. We also can’t use string stream because it loses the last name in the process. the text in the file includes fields separated by delimiters # (with exception to the last field which ends with a newline. for the name field I used this:
/* we already declared an ifstream inputFile and opened it. */
while(!inputFile.eof())
{
string temp;
getline(inputFile, temp, '#');
int size=temp.size();
int i=0;
while (i<size)
{
data.name[i]=temp[i];
i++;
}
}
data.name[i]=0;
inputFile.close();
Komal12
3,2674 gold badges15 silver badges25 bronze badges
answered May 2, 2012 at 18:06
user1066524user1066524
3432 gold badges11 silver badges23 bronze badges
starling 0 / 0 / 0 Регистрация: 08.01.2015 Сообщений: 31 |
||||
1 |
||||
16.11.2016, 00:02. Показов 1941. Ответов 14 Метки нет (Все метки)
Не компилируеться, подчеркивает strcpy в чем может быть ошибка?
__________________
0 |
14 / 14 / 16 Регистрация: 26.01.2015 Сообщений: 213 |
|
16.11.2016, 00:08 |
2 |
starling, попробуй strcpy_s использовать вместо strcpy
0 |
MrGluck Форумчанин 8193 / 5043 / 1437 Регистрация: 29.11.2010 Сообщений: 13,453 |
||||||||
16.11.2016, 00:13 |
3 |
|||||||
Все хедеры подключены?
?
starling, попробуй strcpy_s использовать вместо strcpy Вредный совет. Сменить стандартную функцию на проприетарную и сделать код непереносимым на ровном месте.
1 |
14 / 14 / 16 Регистрация: 26.01.2015 Сообщений: 213 |
|
16.11.2016, 00:19 |
4 |
MrGluck, про define не знал..слышал,что использование strcpy небезопасно
0 |
0 / 0 / 0 Регистрация: 08.01.2015 Сообщений: 31 |
|
16.11.2016, 16:39 [ТС] |
5 |
Не помогает ничего( Это единственный способ использования для ввода char?
0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
16.11.2016, 17:13 |
6 |
Не помогает ничего Что не помогает?
0 |
0 / 0 / 0 Регистрация: 08.01.2015 Сообщений: 31 |
|
16.11.2016, 21:40 [ТС] |
7 |
добавление библиотеки, и тот define что выше? вернее библиотека убрала одну ошибку хотя код вроде как чистый) Миниатюры
0 |
TheCalligrapher Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,098 |
||||||||
16.11.2016, 22:06 |
8 |
|||||||
Сообщение было отмечено starling как решение Решение
?
«После хедеров»? Ключевой момент тут в том, что Добавлено через 1 минуту
добавление библиотеки, и тот define что выше?
2 |
Форумчанин 8193 / 5043 / 1437 Регистрация: 29.11.2010 Сообщений: 13,453 |
|
16.11.2016, 22:17 |
9 |
надо делать именно до (!) включения заголовочных файлов. Да, я был не прав. Привык добавлять в настройках проекта.
0 |
gray_fox |
16.11.2016, 22:22
|
Не по теме:
Вредный совет. Сменить стандартную функцию на проприетарную и сделать код непереносимым на ровном месте. Однако в С11 подобные «safe» варианты таки добавили.
0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
16.11.2016, 22:41 |
11 |
Однако в С11 подобные «safe» варианты таки добавили. Разве?
0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
16.11.2016, 22:57 |
14 |
Тут есть описание Там то есть, в стандарте не нахожу. Добавлено через 2 минуты
0 |
What a waste! 1607 / 1299 / 180 Регистрация: 21.04.2012 Сообщений: 2,727 |
|
16.11.2016, 23:02 |
15 |
Не по теме:
Разве? Там, кстати,по сравнению с VC++, надо делать всё наоборот: определять константу до включения заголовочного файла что бы функция была доступна. + это опциональная фича стандарта, т.е. надо ещё проверить, что эта функция есть в реализации стандартной библиотеки. Добавлено через 32 секунды
Или имеется ввиду Cи-стандарт? Да, С11 — стандарт языка С.
0 |
- Remove From My Forums
-
Question
-
So I’m creating a program that will take the textbox input from the user and will convert it to Unicode and dislpay it.
What is the function in Visual C++ 2010 Express to convert a string to unicode?
Answers
-
On 31/07/2011 06:30, Intense Tactics wrote:
when #include «Windows.h» and #include<string> is added
error C3861: ‘strcpy_s’: identifier not found
Try adding #include <string.h> .
Note that if you use precompiled headers in your project, you could add these #includes directly in the precompiled header «StdAfx.h» file.
If you want to add #include’s explicitly in the source files, you should add these #include lines
after the #include «StdAfx.h» line, e.g.#include «StdAfx.h»
#include <string.h>
#include <string>
…
Giovanni-
Marked as answer by
Friday, August 5, 2011 12:59 AM
-
Marked as answer by
Pacient& operator = ( Pacient&p) {
cout << "Operator = Pacient" << endl;
delete [] this->nume;
this->nume = new char[strlen(p.nume)+1];
strcpy_y(this->nume,strlen(p.nume)+1,p.nume); // ERROR
delete [] this->prenume;
this->prenume = new char[strlen(p.prenume)+1];
strcpy_y(this->prenume,strlen(p.prenume)+1,p.prenume); // ERROR
this->varsta = p.varsta;
return *this;
}
1>Compiling…
1>pacienti.cpp
1>f:bobfacultatesemestrul iiiprogramareorientataobiectproiect pacientiproiectproiectpacienti.cpp(24) : error C3861: ‘strcpy_y’: identifier not found
1>f:bobfacultatesemestrul iiiprogramareorientataobiectproiect pacientiproiectproiectpacienti.cpp(27) : error C3861: ‘strcpy_y’: identifier not found
I get this error. Why? What should I do to get rid of it?
The compiler doesn’t know what strcpy_y
is because you haven’t declared it anywhere prior to that line in the current translation unit.
Either provide the declaration for strcpy_y
(e.g. #include
a relevant header, or forward declare it), or fix the typo if you meant to call some other function.
Recommended Answers
Just because
''
is added automatically doesn’t mean you can’t refer to it explicitly. The code is perfectly legal C, but I suspect the OP is compiling it as C++ wherestring
is very likely to cause issues due to potentially being exposed as a type name.The code as …
Jump to Post
g++
doesn’t complain about the OP’s code, even if I add#include <string>
andusing std::string
.But you didn’t compile the code as it is, because it’s only a snippet; you had to add scaffolding for it to compile. I bet you’re assuming that the …
Jump to Post
Keep in mind we are dealing with C here and not C++.
Just because it’s in the C forum doesn’t mean the OP isn’t using some subset of C++ or compiling as C++. The error strongly suggests that
string
isn’t being parsed as an object. Given that C++ …
Jump to Post
All 11 Replies
9 Years Ago
It doesn’t like the . Try x00 or leave the off.
9 Years Ago
A string using double quotes automatically includes an null character () at the end. So it is trying to copy 7 characters into 6 spaces, 5 for HELLO and 2 null characters. Avoid using the null character in the string literal.
deceptikon
1,790
Code Sniper
Administrator
Featured Poster
9 Years Ago
Just because ''
is added automatically doesn’t mean you can’t refer to it explicitly. The code is perfectly legal C, but I suspect the OP is compiling it as C++ where string
is very likely to cause issues due to potentially being exposed as a type name.
The code as it stands is fine. A more complete example would help in diagnosing this error.
Try x00 or leave the off.
''
and 'x00'
are synonymous.
So it is trying to copy 7 characters into 6 spaces, 5 for HELLO and 2 null characters. Avoid using the null character in the string literal.
strcpy
stops copying at the first null character, so the problem you’ve described does not exist.
Edited
9 Years Ago
by deceptikon
sepp2k
378
Practically a Master Poster
9 Years Ago
I suspect the OP is compiling it as C++ where string is very likely to cause issues due to potentially being exposed as a type name.
Why would it be likely to cause issues in C++? g++
doesn’t complain about the OP’s code, even if I add #include <string>
and using std::string
.
A more complete example would help in diagnosing this error.
Definitely.
deceptikon
1,790
Code Sniper
Administrator
Featured Poster
9 Years Ago
g++
doesn’t complain about the OP’s code, even if I add#include <string>
andusing std::string
.
But you didn’t compile the code as it is, because it’s only a snippet; you had to add scaffolding for it to compile. I bet you’re assuming that the OP’s example is something along the lines of this (assuming C++):
#include <string>
using namespace std;
int main()
{
char string[6];
strcpy(string, "HELLO");
}
Which compiles just fine in Visual Studio (boo for intrinsics), and probably would in g++ as well. However, it could very easily be this:
#include <string>
using namespace std;
char string[6];
int main()
{
strcpy(string, "HELLO");
}
Which pukes with an ambiguity error. That’s why more code is needed to diagnose this issue. When using variable names that could potentially be macro or type names, the exact usage is very important.
sepp2k
378
Practically a Master Poster
9 Years Ago
Which compiles just fine in Visual Studio
TIL: Visual Studio’s <string>
header includes <cstring>
(or at least somehow declares strcpy
). But yes, that’s pretty much what I tried in gcc.
However, it could very easily be this
Interesting, that does indeed cause an error. In fact it produces the exact error message the OP complained about. So that’s almost definitely it.
So I assume the rule is if there’s a type and a variable with the same name, the compiler picks the one with the closer scope (i.e. it will prefer local names over global ones and, presumably, names local to, say, a loop over names local to the whole function) and if the scope is the same, it will always interpret it as a type name? I did not know that. Thank you.
9 Years Ago
Keep in mind we are dealing with C here and not C++. I wonder if the OP did not include <string.h>
for the C prototype of strcpy
. The error message is indicating that the compiler is expecting a closing bracket. If you do not include the correct header file, the C compiler usually makes an assumption about the prototype of the function.
In MS-Visual Studio, I get warning C4013: ‘strcpy’ undefined; assuming extern returning int when I leave out the <string.h>
header file. I wonder if the OP’s compiler is assuming a one-parameter prototype, like extern int strcpy(char *x)
as opposed to extern int strcpy()
, which knows nothing about its indefinite number of parameters.
When it reaches the second parameter, perhaps it does not know what to do with it, but this is just speculation. What compiler is being used on what operating system?
deceptikon
1,790
Code Sniper
Administrator
Featured Poster
9 Years Ago
Keep in mind we are dealing with C here and not C++.
Just because it’s in the C forum doesn’t mean the OP isn’t using some subset of C++ or compiling as C++. The error strongly suggests that string
isn’t being parsed as an object. Given that C++ supports a string type with the name string
, it’s not unreasonable to question which language we’re working with here.
I wonder if the OP’s compiler is assuming a one-parameter prototype, like extern int
strcpy(char *x)
as opposed toextern int strcpy()
, which knows nothing about its indefinite number of parameters.
That’s reaching a bit. Any compiler that assumes the former rather than the latter is broken and non-conforming. I know for a fact that Visual C++ is conforming in this case.
Besides, with a mismatch between the call and definition given an implicit declaration, the actual error would happen at link time rather than the compile time syntax error the OP is seeing.
Edited
9 Years Ago
by deceptikon
sepp2k
378
Practically a Master Poster
9 Years Ago
I wonder if the OP’s compiler is assuming a one-parameter prototype
When a function is implicitly declared in C, the inferred prototype will have the same number of arguments as the function call (and all of the arguments’ types will be int
).
Also the arity of a function is not information that’s relevant to the parser, so calling a function with the wrong number of arguments can’t cause a parse error. It would produce a «wrong number of arguments» error at a later stage of the compilation.
Whether a given identifier refers to a type on the other hand is relevant to the parser, so that can cause a parse error.
9 Years Ago
I agree that I am reaching quite a bit with that explanation. Okay, I still have the code I tested as C code, so I will recompile it as C++ and watch what happens.
Time passes
Ah, nuts! I get error C3861: ‘strcpy’: identifier not found under C++ without #include <string.h>
. If I include the C header file, it compiles fine and executes as expected. Something else is going on here.
Could the original poster include the rest the function in question? We need more context to be able to diagnose the issue, or at least I do.
Edited
9 Years Ago
by Nutster
8 Years Ago
With reference to ur query,
int main()
{
char str[6];
clrscr();
strcpy(str,"Hello");
printf("%s",str);
getch();
return 0;
}
whenever we are passing the string (normal string without ) to another string with the help of strcpy() function it will print as it is.
if ur using at end of the string it is treated as end point,so whenever nul() character is occur it will treat as the termination (end) of the string.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
|
|
|
Работа со структурами+strcpy
, из char в char
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Добрый день.
#include <stdio.h> #include <string.h> #define NAME_SIZE 256 typedef struct { int id; char name[NAME_SIZE]; } Data; int main(){ Data postoi[100]; printf(«Vvedite nomer»); scanf(«%d», &postoi->id); printf(«Vvedite bykvi»); scanf(«%s», postoi->name); printf(«%d%s», postoi->id, postoi->name); printf(«Zapisano v stryktyry postoin»); char tempa[NAME_SIZE]; tempa = *postoi->name; // strcpy(tempa, postoi->name); эта строка в Visual Studio не катит printf(«Perezapisano vo vremenyu peremenyu, %sn», tempa); Data vremennai[100]; strcpy(vremennai->name, tempa); printf(«Zapisano v novyu stryktyry%sn», vremennai->name); int p; scanf(«%d», &p); return 0; } Суть проблемы, хочу записать из структуры символы в переменную, потом из переменной, переписать символы в новую структуру. У меня по ходу проблема с осознанием значений указателей и адресов…Подскажите, как правильно выполнить копирование. И правильно ли здесь используются указатели? |
cppasm |
|
Начни с прочтения какой-нибудь книжки. Добавлено 04.07.11, 10:47 Цитата muskos @ 04.07.11, 10:23 tempa = *postoi->name; Вместо этого должно быть:
strncpy(tempa, postoi[N].name, sizeof(tempa)); tempa[sizeof(tempa)/sizeof(tempa[0])-1]=0; или просто
strncpy(tempa, postoi[N].name, 100); tempa[99]=0; Где N — индекс элемента массива с которым ты хочешь работать. |
awax |
|
Full Member Рейтинг (т): 5 |
Ты пишешь:
tempa = *postoi->name; tempa имеет тип char*, postoi->name имеет тип char*, но ты это дело разыменовываешь и получаешь char. Стоит ли удивляться, что компилятор выдает ошибку? |
muskos |
|
awax, какой строчкой я это делаю? |
awax |
|
Full Member Рейтинг (т): 5 |
Той, что находится перед закомментированной Сообщение отредактировано: awax — 04.07.11, 11:11 |
muskos |
|
Я хотел вот cppasm’у сказать ещё… Добавлено 04.07.11, 11:13 |
awax |
|
Full Member Рейтинг (т): 5 |
Закомментируй ее, а ту что закомментирована, разкомментируй. |
muskos |
|
в Devc++ работает |
awax |
|
Full Member Рейтинг (т): 5 |
Компилируется? |
cppasm |
|
Цитата muskos @ 04.07.11, 10:23 strcpy(tempa, postoi->name);
Вот это не работает, postoi — это массив, а не структура. |
muskos |
|
to awax сорри, что долго у самого вс нету( Саздаём файл, в него записываем структуры…там к примеру имя фамилия и номер… У чувака логика… И вот он меня спрашивает…надо переписать структуру во временную переменную, для пузырька. Сам я с методом не знаком. ПС НИКИТА ЗАРЕГЕСТРИРУЙСЯ НА ФОРУМЕ И САМ ПЕЧАТАЙ БУКВИ!!! Добавлено 04.07.11, 11:41 Добавлено 04.07.11, 11:44 Добавлено 04.07.11, 11:44 |
cppasm |
|
Цитата muskos @ 04.07.11, 11:40 error C3861: ‘strcpy’: identifier not found #include<string.h> есть? Цитата muskos @ 04.07.11, 11:40 И вот он меня спрашивает…надо переписать структуру во временную переменную, для пузырька. Ты не всю структуру переписываешь, а только строку из неё. |
muskos |
|
to cppasm 2)Да я понял, что только эту строку…так я и пытаюсь реализовать сохранение текста из строки во временную переменную |
Nik198 |
|
#include <stdio.h> #include <string.h> #include <stdafx.h> #define NAME_SIZE 256 typedef struct { int id; char name[NAME_SIZE]; } Data; int main(){ Data postoi[100]; for (int i=1;i<4;i++){ printf(«Vvedite nomer»); scanf(«%i»,&postoi[i].id); printf(«Vvedite bykvi»); scanf(«%s»,postoi[i].name); } char temp[NAME_SIZE]; temp=postoi[1].name // Вопрос в этой строчке postoi[1].name=postoi[2].name // И в этой. printf(«Perezapisano vo vremenyu peremenyu, %sn», temp); int p; scanf(«%d», &p); return 0; } Мой вопрос как правильно переменной temp присвоить значение поля name из структуры и postoi[1].name=postoi[2].name и это правельно написать. |
spy_ |
|
Full Member Рейтинг (т): 5 |
Nik198, гугли strcpy(). И прочитай уже хотя бы одну книжку по С. Добавлено 04.07.11, 13:16 |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- C/C++: Общие вопросы
- Следующая тема
[ Script execution time: 0,0598 ] [ 16 queries used ] [ Generated: 9.02.23, 12:13 GMT ]
3 ответа
Нет такой вещи, как strcpy_y
, по крайней мере, не в стандарте C++.
Возможно, вы имели в виду strcpy_s
из WINAPI?
Если strcpy_y
— это функция, которую вы создали сами, вам нужно #include
файл, в котором он был объявлен.
Зачем использовать исходные строки C-стиля? Просто используйте std::string
выделенную как переменную locat, и все эти проблемы исчезнут. Используйте operator=
для копирования string
s.
John Dibling
14 янв. 2014, в 17:43
Поделиться
Компилятор не знает, что такое strcpy_y
, потому что вы не объявили его нигде до этой строки в текущем блоке перевода.
Либо strcpy_y
объявление для strcpy_y
(например, #include
соответствующий заголовок, либо переадресовать его объявление), либо исправьте опечатку, если вы хотите вызвать другую функцию.
JBentley
14 янв. 2014, в 16:38
Поделиться
Я думаю, что это может помочь вам: #include <string.h>
Но я не рекомендую использовать strcpy_y в вашем коде, потому что это не C++.
Yudaev Alexander
14 янв. 2014, в 17:55
Поделиться
Ещё вопросы
- 0Как AngularJS способен различать эти два свойства?
- 1Как отправить текст в поле Email с помощью Selenium и Python
- 0Функция стиля нг и встроенный вместе
- 1Android — заполнение ListView с массивом
- 1Возможность изменения элементов ArrayList
- 1Лучшая реляционная база данных для хранения 1 миллиарда записей
- 0Слэши автоматически добавляются в текстовые поля php
- 1ASP.NET MVC5 — маршрутизируемая страница загружается, но не запускается
- 1Отключить индикатор свечения индикатора выполнения
- 1Изменить конфигурацию мобильной точки доступа
- 0NGINX — PHP-FPM Служба поиска фильмов и дескриптор соединения
- 0FullCalendar: открыть событие gcal в новой вкладке / окне
- 1Форматирование XML для отображения в TextView?
- 0Где мои дивы идут не так?
- 1Как реализовать интерфейс, используя член класса?
- 0Eclipse for PHP error Java была запущена, но вернула код ошибки 13
- 1Webbrowser — избавиться от ошибки
- 1Есть ли стандартный ImageViewer на Android?
- 0$ Scope.Form undefined angularjs
- 1Проблема Android MediaPlayer
- 0JQuery отложено не работает на Chrome и Safari?
- 0JS Установка атрибута onclick разными способами
- 1Операция со списком файлов не удалась после нескольких раундов
- 1Разве shutil.copyfile не должен заменять ссылку в dst с установленным follow_symlinks?
- 0Не могу заставить мой алгоритм сжатия работать правильно
- 0ИЛИ условие в регулярном выражении
- 1Android C2DM навигации по исходному коду JumpNote
- 0Данные MySQL не отображаются в соответствии с идентификатором в таблице HTML
- 1Как создать две взаимодействующие, но не блокирующие службы в Android?
- 0Phalcon PHP NativeArray для доступа к многомерному массиву с помощью шаблона Volt
- 0Выполните первоначальную настройку и разрешите изменения позже в приложении Angular
- 0Если пользовательский интерфейс провайдера перенаправляет на определенный шаблон, и мне нужно проверить аутентификацию и перенаправить на панель инструментов.
- 0PHP — preg_match для проверки формата даты мм / гггг
- 1Android Camera Preview вопрос
- 0Почему эти стилистические ссылки появляются в моем разделе заголовка приложения угловых материалов
- 1Загрузить файл на сервер Apache
- 1почему python не возвращает ничего после расчета? [Дубликат]
- 0Утечка памяти с динамическим массивом переменных mpfr в c ++
- 0Как создать несколько таблиц HTML с динамическими идентификаторами таблиц в XSLT
- 1Использование вложенной переменной в не вложенном аргументе
- 1Null MultiPartConfig при создании GrizzlyHttpServer
- 1Comapring два объекта не вызывает метод CompareTo
- 1Та же строка Привязка данных списка, вызывающая странное поведение элемента управления ComboBox
- 0Есть ли способ получить следующий вывод в SQL
- 1Как не отправлять поле данных в базу данных Java & Microsoft Access
- 1Свойство ‘do’ не существует для типа ‘Подписка’
- 1Основная проблема OpenGL ES Texture / Android
- 0создать копию таблицы Google Doc, используя PHP API
- 1WPF: отключить DropShadow / BitmapEffects для ComboBox
- 0Где найти таблицу в codeigniter?
Я нашел решение, которое сработало для меня. если у вас возникли проблемы, как у меня с strcpy, вы можете использовать size(), чтобы определить размер строки, а затем использовать цикл while, чтобы пройти и добавить его в массив символов. это то, что в конечном итоге сработало для меня:
скажем, у нас есть член структуры данных с массивом символов data.name[30], и у нас есть два слова в файле, которые составляют имя (первое и последнее), и мы не можем просто добавить его в массив символов с помощью strcpy . Мы также не можем использовать строковый поток, потому что он теряет последнее имя в процессе. текст в файле включает поля, разделенные разделителями # (за исключением последнего поля, которое заканчивается новой строкой. для поля имени я использовал это:
/* we already declared an ifstream inputFile and opened it. */
while(!inputFile.eof())
{
string temp;
getline(inputFile, temp, '#');
int size=temp.size();
int i=0;
while (i<size)
{
data.name[i]=temp[i];
i++;
}
}
data.name[i]=0;
inputFile.close();
Pacient& operator = ( Pacient&p) {
cout << "Operator = Pacient" << endl;
delete [] this->nume;
this->nume = new char[strlen(p.nume)+1];
strcpy_y(this->nume,strlen(p.nume)+1,p.nume); // ERROR
delete [] this->prenume;
this->prenume = new char[strlen(p.prenume)+1];
strcpy_y(this->prenume,strlen(p.prenume)+1,p.prenume); // ERROR
this->varsta = p.varsta;
return *this;
}
1> Компиляция …
1> pacienti.cpp
1> f: bob facultate semestrul iii programareorientataobiect proiect pacienti proiect proiect pacienti.cpp (24): ошибка C3861: ‘strcpy_y’: идентификатор не найден
1> f: bob facultate semestrul iii programareorientataobiect proiect pacienti proiect proiect pacienti.cpp (27): ошибка C3861: ‘strcpy_y’: идентификатор не найден
Я получаю эту ошибку. Зачем? Что я должен сделать, чтобы избавиться от этого?
0
Решение
Компилятор не знает что strcpy_y
потому что вы не объявили это нигде до этой строки в текущей единице перевода.
Либо предоставьте декларацию для strcpy_y
(например. #include
соответствующий заголовок, или форвард объявите его), или исправьте опечатку, если вы хотели вызвать какую-то другую функцию.
2
Другие решения
Там нет такого понятия, как strcpy_y
По крайней мере, не в стандарте C ++.
Возможно, вы имели в виду strcpy_s
из Винапи?
Если strcpy_y
это функция, которую вы создали сами, то вам нужно #include
файл, в котором он объявлен.
Зачем использовать необработанные строки в стиле C? Просто используйте std::string
выделяется как переменная locat, и все эти проблемы исчезают. использование operator=
скопировать string
s.
2
Я думаю, что это может помочь вам:
#include <string.h>
Но я не рекомендую использовать strcpy_y в вашем коде, потому что это не C ++.
0