Error implicit declaration of function itoa

When I try use the function itoa(), I get the warning: implicit declaration of function is invalid in c99. I have included stdlib.h on my header. I'm trying to call this function inside a func...

When I try use the function itoa(), I get the warning:

implicit declaration of function is invalid in c99.

I have included stdlib.h on my header. I’m trying to call this function inside a function, I’m not sure if this is allowed.

Brian's user avatar

Brian

13.9k7 gold badges34 silver badges43 bronze badges

asked Apr 15, 2012 at 13:30

maxflow's user avatar

3

The problem is that itoa() isn’t a standard function.

You should take a look at this link which gives you some alternative implementations

Hong Ooi's user avatar

Hong Ooi

55.8k13 gold badges130 silver badges182 bronze badges

answered Apr 15, 2012 at 13:41

Marco's user avatar

MarcoMarco

2,73617 silver badges24 bronze badges

3

An alternative that is commonly used in place of itoa is sprintf/snprintf. These are part of stdio.h.

answered Apr 15, 2012 at 13:52

Mike Kwan's user avatar

Mike KwanMike Kwan

23.9k12 gold badges62 silver badges96 bronze badges

As @Mike Kwan pointed out. Sprintf can be used as follows,

int load = 15;
char buffer[100];

sprintf(buffer,"%d",load);

printf("buffer in int = %sn",buffer);

answered Apr 8, 2022 at 21:19

Deekshith Patil's user avatar

0

#c

Вопрос:

Почему я получаю warning: implicit declaration of function 'itoa' ошибку? Я проверил заголовочные файлы и код. stdlib.h уже добавлен в директивы. Я совершенно не понимаю, почему продолжает появляться предупреждение/ошибка.

Мне нужно изменить заданную дату СИМВОЛА в формате ММ/ГГ на ЧИСЛО ГГГГММДД. Я использовал функцию, которая принимает переменную MM/YY в качестве параметра и разбивает ее на отдельные переменные, а затем объединяет их в одну переменную.

 #includelt;stdio.hgt; #includelt;string.hgt; #includelt;stdlib.hgt;  int getNumDate (char *date);    int main() {  char prodDate[5   1];  strcpy(prodDate,"03/12");    printf("%d", getNumDate(prodDate));    return 0; }   int getNumDate (char *date) {  static char orig_mmyy[5   1];  static char *str_ptr;  static char *c_yy = NULL;  static char *c_mm = NULL;  static char *c_dd = NULL;  char new_yy[4   1];  char new_mm[2   1];  char new_dd[2   1];  strcpy(new_dd, "01");  char finalDate_chars[8   1];  int finalDate;    strcpy(orig_mmyy, date);//store original MM/YY  str_ptr = orig_mmyy;//copy MM/YY to str_ptr  c_mm = strtok(str_ptr, "/");//store MM  c_yy = strtok(NULL, "/");//store YY  c_dd = "01";//set DD  if( atoi(c_yy) lt; 65 )//1965 is the Go Date -- less than 65 must be 21st Century  {   //****ERROR OCCURS HERE****//  itoa(atoi(c_yy)   2000, new_yy, 10);//convert YY to YYYY and copy to new YYYY  }  else  {  itoa(atoi(c_yy)   1900, new_yy, 10);//convert YY to YYYY for 20th Century (1900s)  }  memcpy(new_mm, c_mm, sizeof(new_mm));//copy new MM  memcpy(new_dd, c_dd, sizeof(new_dd));//copy new DD    strcat(finalDate_chars,new_yy);  strcat(finalDate_chars,new_mm);  strcat(finalDate_chars,new_dd);  finalDate = atoi(finalDate_chars);    return finalDate; }   

Комментарии:

1. itoa() не является стандартной функцией C, поэтому может отсутствовать в библиотеке вашей реализации.

Ответ №1:

В itoa стандарте C. нет функции, которую вы можете использовать snprintf вместо этого.

Кроме того, atoi доступен в стандарте C, но использовать его не рекомендуется, поскольку он не позволяет надежно обнаруживать ошибки. strtol вместо этого рекомендуется.

Комментарии:

1. Как snprintf может преобразовать число обратно в строку?

2. @JaguarNation: Эти функции хорошо документированы, и вы можете найти примеры по всему Интернету. (Поскольку snprintf вы можете найти больше примеров с sprintf , которые похожи, но менее безопасны, потому что это затрудняет предотвращение переполнения буфера; эти примеры было бы легко адаптировать.) Если у вас возникнут конкретные вопросы при чтении документации или примеров, пожалуйста, найдите здесь, чтобы узнать, даны ли на них ответы, а если нет, задайте их в качестве нового вопроса (а не в качестве комментариев к этому сообщению).

3. Хорошие моменты о том, что включено в стандарт C. Я думаю, что sscanf хорош для преобразования строк в int, а sprintf будет работать для преобразования int в строку. Спасибо.

4. Да, sscanf также может использоваться вместо strtol . Если вы используете sprintf вместо snprintf этого, вы должны быть очень осторожны, чтобы убедиться, что ваш буфер достаточно велик для максимально длительного вывода, и может быть трудно определить, насколько это может быть долго. Вот почему я не рекомендую этого делать.

5. @JaguarNation: Одна из проблем sscanf заключается в том, что если строка содержит цифры, которые образуют действительное число, но это число слишком велико для int (или любого другого указанного вами типа), то стандарт C говорит, что поведение неопределенно, что было бы очень плохо. Большинство реальных реализаций будут вести себя разумно в таком случае, но это затрудняет правильную обработку ошибок.

Когда я пытаюсь использовать функцию itoa(), Я получаю предупреждение:

неявное объявление функции недопустимо в c99.

Я включил stdlib.h в свой заголовок. Я пытаюсь вызвать эту функцию внутри функции, я не уверен, что это разрешено.

2 ответы

Проблема в том, что itoa() не является стандартной функцией.

Вы должны взглянуть на эту ссылку который дает вам несколько альтернативных реализаций

Создан 10 июля ’13, 18:07

Альтернатива, которая обычно используется вместо itoa is sprintf/snprintf. Это часть stdio.h.

ответ дан 15 апр.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

c

or задайте свой вопрос.

    msm.ru

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

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

    >
    как использовать itoa(,,) в никсах

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



    Сообщ.
    #1

    ,
    19.10.05, 16:23

      Member

      **

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

      в Винде пишу так

      ExpandedWrap disabled

        void addVar(const std::string& name,const ULONG value)

        {

         var t;

         t.name = name;

         char tmv[30];

         itoa(value,tmv,10);

         t.value = tmv;

         vvar.push_back(t);

        };

      всё работает. в никсах выдаёт
      templater.cpp: In method `void Variable::addVar(const string &, long unsigned int)’:
      templater.cpp:51: implicit declaration of function `int itoa(…)’

      понятно, что не может найти определение итоа.
      не понятно где его взять.
      подскажите как компилировать с этой функцией


      stontaro



      Сообщ.
      #2

      ,
      19.10.05, 16:58

        man sprintf


        freeuser



        Сообщ.
        #3

        ,
        19.10.05, 20:11

          Member

          **

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

          когда я стал использовать

          ExpandedWrap disabled

            #include <stdlib.h>

            extern «C» char *itoa( int , char *, int);

          то всё стало работать. спасибо за помощь bkrot

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

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

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

          Рейтинг@Mail.ru

          [ Script execution time: 0,0319 ]   [ 16 queries used ]   [ Generated: 9.02.23, 13:56 GMT ]  

          Problem:

          While trying to compile your C/C++ program, you see an error message like

          ../src/main.c:48:9: error: implicit declaration of function 'StartBenchmark' [-Werror=implicit-function-declaration]
                   StartBenchmark();

          Solution:

          implicit declaration of function means that you are trying to use a function that has not been declared. In our example above, StartBenchmark is the function that is implicitly declared.

          This is how you call a function:

          StartBenchmark();

          This is how you declare a function:

          void StartBenchmark();

          The following bullet points list the most common reasons and how to fix them:

          1. Missing #include: Check if the header file that contains the declaration of the function is #included in each file where you call the function (especially the file that is listed in the error message), before the first call of the function (typically at the top of the file). Header files can be included via other headers,
          2. Function name typo: Often the function name of the declaration does not exactly match the function name that is being called. For example, startBenchmark() is declared while StartBenchmark() is being called. I recommend to fix this by copy-&-pasting the function name from the declaration to wherever you call it.
          3. Bad include guard: The include guard that is auto-generated by IDEs often looks like this:
            #ifndef _EXAMPLE_FILE_NAME_H
            #define _EXAMPLE_FILE_NAME_H
            // ...
            #endif

            Note that the include guard definition _EXAMPLE_FILE_NAME_H is not specific to the header filename that we are using (for example Benchmark.h). Just the first of all header file names wil

          4. Change the order of the #include statements: While this might seem like a bad hack, it often works just fine. Just move the #include statements of the header file containing the declaration to the top. For example, before the move:
            #include "Benchmark.h"
            #include "other_header.h"

            after the move:

            #include "Benchmark.h"
            #include "other_header.h"

          Понравилась статья? Поделить с друзьями:
        • Error implicit declaration of function getline
        • Error imei huawei e1550
        • Error image type not supported
        • Error image is not a valid ios image archive
        • Error image id roblox