【问题标题】:Get the value from string vecotr and store in another string?从字符串向量中获取值并存储在另一个字符串中?
【发布时间】:2013-10-11 10:56:28
【问题描述】:

我正在尝试将字符串值存储到向量中。然后在存储之后我想一个一个地存储在字符串中。在第一步中,将字符串拆分为“,”并存储到向量中。并再次尝试检索并进入字符串。

我的代码:

CString sAssocVal = "test1, test2, test3";

istringstream ss( sAssocVal.GetBuffer(sAssocVal.GetLength()) );

vector<string> words;


string token;
while( std::getline(ss, token, ',') )
{
    words.push_back( token );
}

尝试再次从向量中检索:

for(int i = 0; i<words.size(); i++)
        std::string st= words[i];

但 st 的值总是为 NULL。

我错过了一些东西。

【问题讨论】:

  • 您是否尝试过在循环之前调试和检查向量包含的内容? “获取 NULL”是什么意思?您如何观察到这一点?
  • 我总是尽可能避免使用 MFC 的CString,问题可能在于您构建istringstream 的方式,您是否尝试输出ss.str()

标签: string visual-c++ vector stl mfc


【解决方案1】:

AFAIK 问题是 istringstream 初始化,一个小的修改使您的示例工作:

http://coliru.stacked-crooked.com/a/698818655cbba4e7

你可以先将 CString 转换为 std::string,关于这个问题的话题很多

【讨论】:

    【解决方案2】:

    我通过使用此代码解决了这个问题。

       CString st;
        for(int i = 0; i<words.size(); i++)
                st= words[i].c_str();
    

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 2015-05-21
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多