Answer the question
In order to leave comments, you need to log in
Why does this code crash on startup?
I want to easily convert strings to numbers and vice versa without unnecessary bicycles.
To do this, I write wrappers for a standard atof(char*)
function from stdlib.h and a non-standard function, the gcc extension, itoa(int, char*, int)
from the same stdlib.h
There were no problems with the first function, but I had to rack my brains with the second.
Here is a working C++ example:
#include <iostream>
#include <cstdlib>
int GetInt( const int &number )
{
char *result;
return itoa(number, result, 10);
}
int main()
{
std::cout << GetInt( 475); // Все прекрасно работает
}
// Numbers.c
#include <stdlib.h>
int GetInt(const int number)
{
char *result;
return itoa(number, result, 10);
}
#include <iostream>
extern "C" int GetInt(const int);
int main()
{
std::cout << GetInt( 475);
// Компилируется, но при запуске сразу вылетает
}
Answer the question
In order to leave comments, you need to log in
I want to easily convert strings to numbers and vice versa without unnecessary bicycles.
#include <iostream>
#include <string>
int main()
{
std::string number = "123456";
int value = std::stoi(number);
std::cout << value; // 123456 (int)
std::string number2 = std::to_string(value);
std::cout << number2; // 123456 (string)
}
And who will allocate memory for the result?
char *result; // не инициализированна
return itoa(number, result, 10);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question