I have a sample c file called itoa.cpp as below:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %sn",buffer);
return 0;
}
When i compile the above code with the below command:
gcc itoa.cpp -o itoa
i am getting this error:
[root@inhyuvelite1 u02]# gcc itoa.cpp -o itoa itoa.cpp: In function "int main()": itoa.cpp:10: error: "itoa" was not declared in this scope
What is wrong in this code? How to get rid of this?
X-Istence
16.2k6 gold badges57 silver badges74 bronze badges
asked Jun 24, 2011 at 3:15
1
itoa is not ansi C standard and you should probably avoid it. Here are some roll-your-own implementations if you really want to use it anyway:
http://www.strudel.org.uk/itoa/
If you need in memory string formatting, a better option is to use snprintf. Working from your example:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
snprintf(buffer, sizeof(buffer), "%d", i);
printf ("decimal: %sn",buffer);
return 0;
}
Vadzim
24.2k11 gold badges137 silver badges149 bronze badges
answered Jun 24, 2011 at 3:21
MikolaMikola
9,0472 gold badges33 silver badges41 bronze badges
0
If you are only interested in base 10, 8 or 16. you can use sprintf
sprintf(buf,"%d",i);
answered Jun 24, 2011 at 3:26
JexcyJexcy
5944 silver badges15 bronze badges
6
Look into stdlib.h. Maybe _itoa instead itoa was defined there.
answered Aug 30, 2012 at 10:33
meldomeldo
2913 silver badges11 bronze badges
1
У меня есть образец файла c с именем itoa.cpp, как показано ниже:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %sn",buffer);
return 0;
}
Когда я компилирую приведенный выше код с помощью следующей команды:
gcc itoa.cpp -o itoa
я получаю эту ошибку:
[root @ inhyuvelite1 u02] # gcc itoa.cpp -o itoa itoa.cpp: в функции «int main ()»: itoa.cpp: 10: ошибка: «itoa» не был объявлен в этой области
Что не так в этом коде? Как от этого избавиться?
3 ответы
itoa не является стандартом ansi C, и вам, вероятно, следует избегать его. Вот несколько собственных реализаций, если вы действительно хотите его использовать:
http://www.strudel.org.uk/itoa/
Если вам нужно форматирование строки памяти, лучшим вариантом является использование snprintf. Работая с вашим примером:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
snprintf(buffer, sizeof(buffer), "%d", i);
printf ("decimal: %sn",buffer);
return 0;
}
Создан 01 июля ’16, 09:07
Если вас интересуют только базы 10, 8 или 16., вы можете использовать sprintf
sprintf(buf,"%d",i);
Создан 24 июн.
Загляните в stdlib.h. Может быть, там был определен _itoa вместо itoa.
ответ дан 30 авг.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
c
or задайте свой вопрос.
adevale 0 / 0 / 0 Регистрация: 30.04.2015 Сообщений: 13 |
||||
1 |
||||
13.05.2015, 16:50. Показов 8149. Ответов 4 Метки нет (Все метки)
в ошибке написано что itoa() не объявлена (itoa() was not declared in this scope)
__________________
0 |
Aleks_Tret 9 / 9 / 13 Регистрация: 25.10.2014 Сообщений: 52 |
||||
13.05.2015, 16:58 |
2 |
|||
0 |
0 / 0 / 0 Регистрация: 30.04.2015 Сообщений: 13 |
|
13.05.2015, 17:08 [ТС] |
3 |
пробовал — не помогает, может это связано с использованием gcc?
0 |
Супер-модератор 32451 / 20945 / 8105 Регистрация: 22.10.2011 Сообщений: 36,213 Записей в блоге: 7 |
|
13.05.2015, 17:13 |
4 |
может это связано с использованием gcc? Однозначно. This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers. gcc в их число не входит…
0 |
4773 / 3267 / 497 Регистрация: 19.02.2013 Сообщений: 9,046 |
|
13.05.2015, 17:33 |
5 |
0 |
- Forum
- Beginners
- Why «itoa» function doesn’t work with C+
Why «itoa» function doesn’t work with C++11 ISO standard?
Hey guys. I have this pretty simple code here:
|
|
However, when I turn on the «Have g++ follow the C++11 ISO language standard» in the compiler options (which I needed earlier to use ‘tuple’ objects) my code won’t compile. I get the «itoa was not declared in this scope» error.
But when I turn it off, the code works.
Why is that so?
Does C++11 not support cstdlib, and if so, why?
There is no
itoa
function in C or C++ standard libs. You are probably using nonstandard extension which was disabled when you explicitely told to adhere to the specific standard. If you want to output something in c-string, use sprintf/snprintf: http://en.cppreference.com/w/cpp/io/c/fprintf
However in C++ there is no reason why you shouldn’t use
std::string
class and
std::to_string
family of functions.
Last edited on
Ah, I get it now. I didn’t know there was such a function for strings, though, when I asked my school professor about it he told me to use itoa.
Thank you
Topic archived. No new replies allowed.
На чтение 3 мин. Просмотров 37 Опубликовано 15.12.2019
Я сделал программу на С ++, которая использует itoa (). Я скомпилировал его на 64-битном компиляторе (TDM-GCC-5.1), он скомпилирован и работает. Но когда я скомпилировал его с использованием 32-битного компилятора TDM-GCC-5.1, я понял, что itoa () не было объявлено в этой области. Я попытался скомпилировать это на двух разных 32-битных машинах, но я получил ту же ошибку, и она включила cstdlib и stdlib.h, но в обоих случаях ошибка одна и та же.
Он компилируется и отлично работает на 64-битной машине. Но почему это не происходит на 32-битном компиляторе?
Можете ли вы предложить какую-нибудь альтернативу для 32-битной?
Содержание
- Решение
- 3 Answers 3
- 3 Answers
Решение
itoa не является стандартной функцией. Это обеспечивается некоторыми реализациями, а не другими. Избегайте этого в портативном программном обеспечении.
64-разрядная версия TDM GCC в режиме по умолчанию обеспечивает itoa, а 32-разрядная — нет. Чтобы сохранить согласованность между версиями, попробуйте, например, -std=c++11 -DNO_OLDNAMES -D_NO_OLDNAMES ,
Соответствующая стандартам альтернатива будет, например,
Говоря о портативности, main() без int Это серьезная ошибка, которая ошибочно остается без диагностики в некоторых версиях GCC для Windows. Это ошибка в этой версии GCC. Кроме того, доступ к неинициализированной переменной test вызывает неопределенное поведение.
I am getting the following error:
prog.cpp: In member function ‘void Sequence::GetSequence()’:
prog.cpp:45: error: ‘itoa’ was not declared in this scope
I have include cstdlib header file but its not working.
3 Answers 3
There’s no itoa in the standard, but in C++11 you can use the std::to_string functions.
In C++11 you can use std::to_string . If this is not available to you, you can use a std::stringstream :
If this is too verbose, there is boost::lexical_cast. There are some complaints about the performance of lexical_cast and std::stringstream , so watch out if this is important to you.
Another option is to use a Boost.Karma, a sublibrary of Spirit. It comes out ahead in most benchmarks.
Usually, itoa is a bad idea. It is neither part of the C nor C++ standard. You can take some care to identify the platforms that support it and use it conditionally, but why should you, when there are better solutions.
im using format itoa(i,string_temp, 10);
atoi is working, but not atoa, why?
yes i include stdlib and stdio. :/
im on mac, if that helps
3 Answers
There is no such thing as itoa() in C++ (or in C, for that matter).
New C++ compilers have std::to_string() which converts integral types to std::string objects, if not, try getting boost for its boost::lexical_cast (), and if not — write your own converter.
std::string str = std::to_string(123);
std::string str = boost::lexical_cast (123);