【问题标题】:UWP Convert String to an IntegerUWP 将字符串转换为整数
【发布时间】:2017-03-05 15:40:31
【问题描述】:

贪婪,

我一直在用谷歌浏览所有内容,但我找不到答案。

如何在通用 Windows 平台 (UWP) 中使用 C++ 将字符串“5”转换为整数 5?

我已经尝试通过 (String^) 转换它,所以,我知道这毫无意义,但你永远不会知道 UWP。

msdn 文档没有描述任何关于类型转换的内容,我只是无法在任何地方找到它。我不想做类似 String ^ => wchar_t => char -> atoi 之类的事情。有没有更好的方法呢?还是我必须做这个漫长的记忆过程?

编辑: 它与您标记的不一样...您可以在标记之前阅读我的描述吗?您发送的链接是将 std::string 转换为整数,这很容易,但我需要知道如何将 String^ 转换为 int (int32)

【问题讨论】:

  • @Sam:我认为他不是在询问转换字符串→int,而是在特殊情况下 UWP String^int。潜在的重复(即stackoverflow.com/questions/194465/…)并未涵盖这一点。
  • 我怀疑Platform::String::Data 成员函数会让您使用普通字符串来int 方法,例如std::stoi。请参阅 (stackoverflow.com/questions/11746146/…)。
  • 好吧,我最终得到了 wcstol,但我正在考虑像 C# 中的 ToInt 之类的东西...不使用 ...tol(str, wcs..) 函数的东西
  • System::Int32::Parse。我什至没有看过 UWP,所以我不知道它是否可用,但如果有,那是相当直接的。
  • @Lukasas 你考虑过使用 C++ 的字符串流吗?

标签: c++ uwp c++-cx


【解决方案1】:

Platform::String(在 C++/CX 中表示为 String^)提供了 String::Data 成员,该成员将 const char16* 返回到内部缓冲区。然后它可以与任何标准的 C 或 C++ 字符串转换函数一起使用,例如 std::wcstol:

long ToLong( String^ str ) {
    const wchar_t* begin = str->Data();
    return std::wcstol( begin, nullptr, 10 );
}

或者,如果你想实现一些错误处理,并确保整个字符串被解释,你可以这样写:

long ToLong( String^ str ) {
    const wchar_t* begin = str->Data();
    const wchar_t* end = str->Data() + std::wcslen( str->Data() );
    wchar_t* last_interpreted{ nullptr };
    long l = std::wcstol( begin, &last_interpreted, 10 );
    if ( last_interpreted != end ) {
        throw ref new InvalidArgumentException();
    }
    return l;
}

注意,没有分配额外的内存。转换函数对存储的Platform::String序列进行操作。

如果您可以节省潜在的临时内存分配,您可以使用std::stol,并免费获得适当的错误报告:

long ToLong( String^ str ) {
    return std::stol( { str->Data(), str->Length() } );
}

【讨论】:

  • std::stoi 提供错误检查,使用非常简单。 :)
  • @Cheersandhth.-Alf:确实如此。但它是由优化器决定的,以产生同样零开销的转换。 const std::wstring 可能(或可能不)必须分配额外的副本。不管怎样,为了完整起见,我会添加它。
猜你喜欢
  • 1970-01-01
  • 2012-02-21
  • 2010-12-31
相关资源
最近更新 更多