Error c3861 strcpy identifier not found

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.

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

user1066524's user avatar

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

dreamlax's user avatar

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's user avatar

Komal12

3,2674 gold badges15 silver badges25 bronze badges

answered May 2, 2012 at 18:06

user1066524's user avatar

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 в чем может быть ошибка?

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
void printHrad(struct hrady hrad) {
        printf("Hrad name: %sn", hrad.Name);
        printf("Hrad age: %dn", hrad.Age);
        printf("Hrad Location: %sn"), hrad.Location;
    }
 
    struct hrady {
        char Name[20];
        char Location[20];
        int Age;
        int rowId;
    } hrad1, hrad2;
 
    int main()
    {
        
        strcpy(hrad1.Name, "Pernstejn");
        hrad1.Age = 1082;
        hrad1.rowId = 1;
        strcpy(hrad1.Location, "Brno-okres");
        printHrad(hrad1);
        
        getchar();
 
        return 0;
    }

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



0



14 / 14 / 16

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

Сообщений: 213

16.11.2016, 00:08

2

starling, попробуй strcpy_s использовать вместо strcpy



0



MrGluck

Форумчанин

Эксперт CЭксперт С++

8193 / 5043 / 1437

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

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

16.11.2016, 00:13

3

Все хедеры подключены?

C++
1
#include <cstring>

?
Если пользуетесь студией, попробуйте добавить после хедеров

C++
1
#define _CRT_SECURE_NO_WARNINGS

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

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

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

Не помогает ничего

Что не помогает?



0



0 / 0 / 0

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

Сообщений: 31

16.11.2016, 21:40

 [ТС]

7

добавление библиотеки, и тот define что выше? вернее библиотека убрала одну ошибку хотя код вроде как чистый)

Миниатюры

Strcpy identifier not found
 



0



TheCalligrapher

Вездепух

Эксперт CЭксперт С++

10435 / 5704 / 1553

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

Сообщений: 14,098

16.11.2016, 22:06

8

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

Решение

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

C++
1
#include <cstring>

?
Если пользуетесь студией, попробуйте добавить после хедеров

C++
1
#define _CRT_SECURE_NO_WARNINGS

«После хедеров»? Ключевой момент тут в том, что #define _CRT_SECURE_NO_WARNINGS надо делать именно до (!) включения заголовочных файлов.

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

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

добавление библиотеки, и тот define что выше?

#define сделайте именно до #include <cstring>. А лучше — прямо в установках проекта.



2



Форумчанин

Эксперт CЭксперт С++

8193 / 5043 / 1437

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

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

16.11.2016, 22:17

9

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

надо делать именно до (!) включения заголовочных файлов.

Да, я был не прав. Привык добавлять в настройках проекта.



0



gray_fox

16.11.2016, 22:22

Не по теме:

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

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

Однако в С11 подобные «safe» варианты таки добавили.



0



3433 / 2812 / 1249

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

Сообщений: 9,426

16.11.2016, 22:41

11

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

Однако в С11 подобные «safe» варианты таки добавили.

Разве?



0



3433 / 2812 / 1249

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

Сообщений: 9,426

16.11.2016, 22:57

14

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

Тут есть описание

Там то есть, в стандарте не нахожу.

Добавлено через 2 минуты
Или имеется ввиду Cи-стандарт? Тогда понятно, почему не нахожу…



0



What a waste!

1607 / 1299 / 180

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

Сообщений: 2,727

16.11.2016, 23:02

15

Не по теме:

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

Разве?

Там, кстати,по сравнению с VC++, надо делать всё наоборот: определять константу до включения заголовочного файла что бы функция была доступна. + это опциональная фича стандарта, т.е. надо ещё проверить, что эта функция есть в реализации стандартной библиотеки.

Добавлено через 32 секунды

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

Или имеется ввиду 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

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++ where string 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> and using 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

Member Avatar

9 Years Ago

It doesn’t like the . Try x00 or leave the off.

Member Avatar

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.

Member Avatar


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

Member Avatar


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.

Member Avatar


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> and using 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.

Member Avatar


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.

Member Avatar

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?

Member Avatar


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 to extern 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

Member Avatar


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.

Member Avatar

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

Member Avatar

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.

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    Работа со структурами+strcpy
    , из char в char

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    04.07.11, 10:23

      Добрый день.
      Помогите разобраться! Уже пролазил в поиске, но даже точно не знаю, где искать.

      ExpandedWrap disabled

        #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;

            }

      Суть проблемы, хочу записать из структуры символы в переменную, потом из переменной, переписать символы в новую структуру.
      На этот код компилятор выдаёт :
      incompatible types in assignment of `char’ to `char[256]’

      У меня по ходу проблема с осознанием значений указателей и адресов…Подскажите, как правильно выполнить копирование. И правильно ли здесь используются указатели?


      cppasm



      Сообщ.
      #2

      ,
      04.07.11, 10:30

        Начни с прочтения какой-нибудь книжки.
        Здесь проще сказать что правильно, чем что неправильно — неправильно практически всё.

        Добавлено 04.07.11, 10:47

        Цитата muskos @ 04.07.11, 10:23

        tempa = *postoi->name;

        Вместо этого должно быть:

        ExpandedWrap disabled

          strncpy(tempa, postoi[N].name, sizeof(tempa));

          tempa[sizeof(tempa)/sizeof(tempa[0])-1]=0;

        или просто

        ExpandedWrap disabled

          strncpy(tempa, postoi[N].name, 100);

          tempa[99]=0;

        Где N — индекс элемента массива с которым ты хочешь работать.


        awax



        Сообщ.
        #3

        ,
        04.07.11, 10:49

          Full Member

          ***

          Рейтинг (т): 5

          Ты пишешь:

          ExpandedWrap disabled

            tempa = *postoi->name;

          tempa имеет тип char*, postoi->name имеет тип char*, но ты это дело разыменовываешь и получаешь char. Стоит ли удивляться, что компилятор выдает ошибку?


          muskos



          Сообщ.
          #4

          ,
          04.07.11, 11:01

            awax, какой строчкой я это делаю?:(


            awax



            Сообщ.
            #5

            ,
            04.07.11, 11:06

              Full Member

              ***

              Рейтинг (т): 5

              Той, что находится перед закомментированной :D
              Закомментируй ее, а ту что закомментирована, разкомментируй.

              Сообщение отредактировано: awax — 04.07.11, 11:11


              muskos



              Сообщ.
              #6

              ,
              04.07.11, 11:12

                Я хотел вот cppasm’у сказать ещё…
                строчка strcpy в визуал студио не работает(
                В деве без того, что awax называет разименовать, работает нормально. Т.е. если раскоментить строчку и убрать разименовывание…
                Так а что делать?:( Как сделать, что бы заработало?

                Добавлено 04.07.11, 11:13
                Там суть вообще, надо сделать пузырьковым методом…Это всё товарисчу. у него не получается сохранить строку из структуры в отдельную строку, что бы потом отпузырить её и удалить…


                awax



                Сообщ.
                #7

                ,
                04.07.11, 11:14

                  Full Member

                  ***

                  Рейтинг (т): 5

                  Закомментируй ее, а ту что закомментирована, разкомментируй.


                  muskos



                  Сообщ.
                  #8

                  ,
                  04.07.11, 11:17

                    в Devc++ работает
                    в Microsoft Visual Studio2008 не работает


                    awax



                    Сообщ.
                    #9

                    ,
                    04.07.11, 11:20

                      Full Member

                      ***

                      Рейтинг (т): 5

                      Компилируется?


                      cppasm



                      Сообщ.
                      #10

                      ,
                      04.07.11, 11:38

                        Цитата muskos @ 04.07.11, 10:23

                        strcpy(tempa, postoi->name);

                        Вот это не работает, postoi — это массив, а не структура.
                        У него нету поля name.
                        Замени на strcpy(tempa, postoi[0].name);
                        Но лучше так как я написал выше.


                        muskos



                        Сообщ.
                        #11

                        ,
                        04.07.11, 11:40

                          to awax сорри, что долго у самого вс нету(
                          error C3861: ‘strcpy’: identifier not found
                          вот что ругает на эту строчку…
                          может есть другой подход…Опишу суть задания и логику…

                          Саздаём файл, в него записываем структуры…там к примеру имя фамилия и номер…
                          надо прочитать из файла…это готово.
                          надо записать в файл…это готово.
                          надо удалить из файла…фатал
                          надо переписать в файле….фатал.
                          Начал с удалить…

                          У чувака логика…
                          Считываем структуры из файла.
                          Узнаём с консоли номер строки для удаления.
                          Потом сортируем пузырьковым методом, что бы структура оказалась последней в массиве.
                          Записываем всё назад в файл, без последней структуры.

                          И вот он меня спрашивает…надо переписать структуру во временную переменную, для пузырька. Сам я с методом не знаком.
                          Я пытался реализовать перепись структуры во временную переменную. Он говорит, что целые числа переписывает на легке, а вот с чарами трабл.

                          ПС НИКИТА ЗАРЕГЕСТРИРУЙСЯ НА ФОРУМЕ И САМ ПЕЧАТАЙ БУКВИ!!!

                          Добавлено 04.07.11, 11:41
                          cppasm спасибо, ща пробую!

                          Добавлено 04.07.11, 11:44
                          тупо в вижуал Си не пашет STRCPY функция из string.h

                          Добавлено 04.07.11, 11:44
                          а я вообще решил выбрать цветы в векторе для пригласительного на свадьбу с моей невестой)


                          cppasm



                          Сообщ.
                          #12

                          ,
                          04.07.11, 11:46

                            Цитата muskos @ 04.07.11, 11:40

                            error C3861: ‘strcpy’: identifier not found

                            #include<string.h> есть?

                            Цитата muskos @ 04.07.11, 11:40

                            И вот он меня спрашивает…надо переписать структуру во временную переменную, для пузырька.

                            Ты не всю структуру переписываешь, а только строку из неё.


                            muskos



                            Сообщ.
                            #13

                            ,
                            04.07.11, 11:50

                              to cppasm
                              да, подкручиваю я библиотеку эту…
                              microsoft visual studio 2005 или 2008 стоит…

                              2)Да я понял, что только эту строку…так я и пытаюсь реализовать сохранение текста из строки во временную переменную


                              Nik198



                              Сообщ.
                              #14

                              ,
                              04.07.11, 12:12

                                ExpandedWrap disabled

                                  #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_



                                Сообщ.
                                #15

                                ,
                                04.07.11, 13:11

                                  Full Member

                                  ***

                                  Рейтинг (т): 5

                                  Nik198, гугли strcpy(). И прочитай уже хотя бы одну книжку по С.

                                  Добавлено 04.07.11, 13:16
                                  muskos, вдруг у тебя там «с» русская? Ггг :) Если у тебя крутая студия, как ты говоришь, то ставь Visual Assist последний какой-нибудь, наводи курсор на strcpy() и брякай кнопку «Go». Она тебе файл покажет, в каком она описана, его и заинклудишь.

                                  0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                                  0 пользователей:

                                  • Предыдущая тема
                                  • C/C++: Общие вопросы
                                  • Следующая тема

                                  Рейтинг@Mail.ru

                                  [ 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= скопировать strings.

                                  2

                                  Я думаю, что это может помочь вам:
                                  #include <string.h>

                                  Но я не рекомендую использовать strcpy_y в вашем коде, потому что это не C ++.

                                  0

                                  Понравилась статья? Поделить с друзьями:
                                • Error c3861 rand
                                • Error c3861 printf identifier not found
                                • Error c3861 min identifier not found
                                • Error c3861 gets идентификатор не найден
                                • Error c3861 getline идентификатор не найден