for each (std::string s in m_intro.text) // std::vector<string>
{
for (int i = 0; i < s.length(); i++)
{
char* chr = &s.at(i);
chr[i+1] = NULL;
std::string t(chr);
// other code is used below not shown as not relivent
}
}
Run Code Online (Sandbox Code Playgroud)
我想从字符串中获取一个字符.我得到的每个字符然后我想变成一个字符串(有一个需要的函数const std::string&)
上面的代码只运行一次,但在第一个循环之后,整个代码s为null.我明白为什么会这样.
我想要的是从s每个循环中获取下一个char 并将其存储为字符串.
Lig*_*ica 10
char* chr = &s.at(i);
chr[i+1] = NULL;
std::string t(chr);
Run Code Online (Sandbox Code Playgroud)
当它char是C字符串(或char数组)的一部分时,您使用了设置下一个元素的正确(如果过时)方法NULL来终止字符串.
但是在这种情况下,这是不相关的; 你只是索引到一个std::string并用它取代所有的角色NULL,这当然不是你的意思.
std::string 有一个构造函数,你可以用它来避免这种肮脏:
std::string t(1, s.at(i));
// ^ ^ ^
// | | |
// string | |
// | |
// of length 1 |
// char |
// |
// each having value s.at(i)
Run Code Online (Sandbox Code Playgroud)
无需乱搞指针或char数组或NULL终止.