【问题标题】:How to convert list element to string?如何将列表元素转换为字符串?
【发布时间】:2015-03-20 00:55:52
【问题描述】:

我尝试在 vs 2013 中将数据绑定到文本块。

但是当我尝试将列表项转换为字符串时遇到了一些问题。

这是来自 vs 的错误信息:

no instance of constructor "std::basic_string<_Elem, _Traits,
_Alloc>::basic_string [with _Elem=wchar_t,
_Traits=std::char_traits<wchar_t>, _Alloc=std::allocator<wchar_t>]"
matches the argument list argument types are:
(std::_List_iterator<std::_List_val<std::_List_simple_types<std::string>>>)

这是我的代码:

list <string> c1;

//Insert Data
c1.push_back("one");
c1.push_back("two");
c1.push_back("three");
c1.push_back("Four");
c1.push_back("Five");
c1.push_back("Six");
c1.push_back("Seven");
c1.push_back("Eight");
c1.push_back("Nine");
c1.push_back("Ten");




//Random data from list

int RandNum = 0 + (std::rand() % 10);

auto en = c1.begin();
advance(c1.begin(), RandNum);

std::wstring s1(*en);

std::string s2(*en);

ENTEXT->Text = s2; //ENTEXT is textblock name

我正在尝试将列表元素传递给文本块,但是这段代码显示了

错误 C2664 : 'void Windows::UI::Xaml::Controls::TextBlock::Text::set(Platform::String ^)' : 无法将参数 1 从 'std::string' 转换为 'Platform ::字符串 ^'

【问题讨论】:

  • 请提供工作代码示例或至少提供更多信息。例如cn是什么?
  • 错误看起来很清楚。您不能从单个列表迭代器创建字符串。推进c1.begin() 不应该编译。
  • std::wstring 没用,避免使用
  • 我认为您实际上想要一个向量。
  • 嗨,我已经更新了我的代码..谢谢

标签: c++


【解决方案1】:
  1. 您使用了错误的变量:en 是迭代器。
  2. 您需要取消引用迭代器:*en
  3. 你不小心把它变成了wstring

应该是这样的:

std::string s2(*en);

顺便说一句,列表元素已经是字符串,你不需要转换任何东西。

要将std::string 转换为Platform::String,您需要使用c_str 成员函数:

ENTEXT->Text = en->c_str();

【讨论】:

  • 实际上我正在尝试将列表元素传递给文本块
【解决方案2】:

自从你写了

“当我尝试将列表项转换为字符串时遇到了一些问题”

而不是专门wstring,我想你的意思是取消引用正确的迭代器并将s2作为普通的std::string复制

int RandNum = 0 + (std::rand() % 10);

auto en = c1.begin();
std::advance(en, RandNum); // Make sure to advance the right iterator

std::string s2(*en);

Example

请注意,上面将创建迭代器指向的列表元素的副本,但是,它已经是std::string(不需要转换)。您可以只使用取消引用的迭代器:

std::cout << *en;

如果您真的是指 string-&gt;wstring 转换(无论出于问题中未解释的原因),您可以写:

int RandNum = 0 + (std::rand() % 10);

auto en = c1.begin();
std::advance(en, RandNum); // ditto

std::wstringstream ws;
ws << en->c_str();
std::wstring s2 = ws.str();

Example

或者,C++11 解决方案(注意-stdlib=libc++ 支持):

//Random data from list

int RandNum = 0 + (std::rand() % 10);

auto en = c1.begin();
advance(en, RandNum);

typedef std::codecvt_utf8<wchar_t> convert_type;
std::wstring_convert<convert_type, wchar_t> converter;
std::wstring converted_str = converter.from_bytes(*en);

Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 2011-01-08
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多