【変換】文字列→数値、数値→文字列【言語】

#include <iterator> // begin end
#include <charconv> // from_chars to_chars

// C++17から使える
// 動的メモリ確保なし、エラーチェックあり

// 文字列→数値
const char text[] = "123456789";
int value;
auto result = std::from_chars( std::begin( text), std::end( text), value);
if( result.ec == std::errc{})
{
	std::cout << value << std::endl;
    // 123456789
}

// 数値→文字列
char out[64]{};
auto result2 = std::to_chars( std::begin(out), std::end(out), 9876);
if( result2.ec == std::errc{})
{
	std::cout << out << std::endl;
    // 9876
}
// 文字列→数値
int value;
if( int.TryParse( "12345", out value))
{
	Console.WriteLine( value);
}

// 数値→文字列
Console.WriteLine( 6789.ToString());
-- 文字列→数値
text = "123"
value = tonumber( text)
print( value)
-- 123

-- 数値→文字列
value = 987
text = value .. ""
print( 987)
-- 987
import "strconv"

// 文字列→数値
// エラーは無視している
value , _ := strconv.Atoi( "123456789")
fmt.Println( value)
// 123456789

// 数値→文字列
text := strcomv.Itoa( 123456789)
fmt.Println( text)
// 123456789
One Comment

Add a Comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です