现在这让我有点困惑,但 std::string::iterator 实际上产生一个 char(由 typeid 显示)。我需要它作为一个字符串。我该怎么做?
#include <string>
#include <iterator>
int main(){
std::string str = "Hello World!";
for( std::string::iterator it = str.begin(); it != str.end(); it++ ){
std::string expectsString(*it); // error
std::string expectsString(""+*it); // not expected result
myFunction(expectsString);
}
}
我正在使用启用了 C++11 的 gcc 5.4.0。
编辑:因为这需要进一步澄清 我想将 *it 转换为字符串。所以我可以将当前迭代的字符用作字符串,而不是 char。 正如我在上面的代码示例中失败的示例所展示的那样,我正在寻找类似的东西
std::string myStr = *it; //error
最佳答案
改用
std::string expectsString(1, *it);
这是一个演示程序
#include <iostream>
#include <string>
int main()
{
std::string str = "Hello World!";
for( std::string::iterator it = str.begin(); it != str.end(); it++ )
{
std::string expectsString( 1, *it );
std::cout << expectsString;
}
std::cout << std::endl;
return 0;
}
它的输出是
Hello World!
关于c++ - 将 string::iterator 转换为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49051825/