How can I upgrade from C ++ to C11?
Details:
- Ubuntu 14.10 32b
- GCC 4.9.1 (Ubuntu 4.9.1-16ubuntu6)
How can I upgrade from C ++ to C11?
Details:
In your specific situation there is nothing to be updated. As per this your comment you use the version 4.9.1 of the GCC , which supports the standard #
C11 .
According to GCC Wiki :
GCC 4.9 Changes: "ISO C11 support is now at a level similar to ISO C99 support."
Basically, you have to change the itoa
function to std::to_string
.
The real problem is to use the itoa
function, it is not a standard function and not works in GCC on Linux ( at least in my case ). A minimum, complete, and verifiable example of this problem might be:
#include <stdio.h>
#include <stdlib.h>
int main (){
int i;
char buffer [10];
printf ("Digite um número: ");
scanf ("%d", &i);
itoa (i, buffer, 10);
printf ("String: %s\n", buffer);
return 0;
}
When you compile, the following message will appear:
$ g++ -std=c++11 main.cpp -o exemplo1
main.cpp: In function ‘int main()’:
main.cpp:9:22: error: ‘itoa’ was not declared in this scope
itoa (i, buffer, 10);
^
$
Note : If the above command returns the error to_string 'is not a member of std , change -std=c++11
to -std=c++0x
.
According to this IBM article , the std::to_string
function is a convenient way to implement what the itoa
function does. The same code, but for C ++, can be done like this:
#include <iostream>
#include <string>
int main(){
int numero;
std::cout << "Digite um número: " << std::endl;
std::cin >> numero;
std::string str = std::to_string(numero);
std::cout << "String " << str << std::endl;
}
If you use Code :: Blocks as the IDE, and the to_string 'message is not a member of std (or similar) to appear for you, do the following:
Settings
➝ Compiler..
Compiler Settings
➝ Compiler Flags
Check the option Have g ++ follow the coming C ++ 0x ISO language standard -std = c ++ 0x .
Compileandrunthecodeagain.Thismaynotworkinspecificsituations,butitusuallydoes.
Attheendoftheday,theproblemwassolvedusingthe sprintf
function, which can be used following way:
#include <string>
#include <iostream>
#define LIMITE 10
int main(){
int numero = 1234567890;
char str[LIMITE];
sprintf(str, "%d", numero);
std::cout << str << std::endl;
}
Note: It is not always recommended to use sprintf
, in this specific case it is known to in advance the size of the variable numero
, so there are no major problems in using it, but in certain situations where the size that a variable can assume (whether reading a file or user input) is not known, to avoid < a href="https://en.stackoverflow.com/q/52555/6454"> leaks use the snprintf
.