gpt4 book ai didi

c++ - 将元素从 listmylist 复制到字符串 mystr

转载 作者:行者123 更新时间:2023-11-28 08:16:59 24 4
gpt4 key购买 nike

list<string> mylist;
mylist.push_back("random stuff");
list<string>::iterator it;
it=mylist.begin();
string mystr;
//and this doesn't work:
mystr=*it;

假设我有一个 list<string> mylist它有 3 个项目。由于我无法处理每个元素的字符,因此我必须将我想要的项目复制到一个简单的字符串或字符缓冲区。但是我根本找不到办法,我也尝试过使用指向数组的指针。那么有没有办法将这些项目从列表中复制出来?

编辑:是的,抱歉,重新访问了我的代码,即项目,发现错误出在其他地方,我在迭代器的帮助下从 listmylist 复制到字符串 mystr,并且我使用的 for 循环的条件是当它遇到我复制它时放置的字符'\0'时停止,它没有复制我的字符串中的'\0'所以最后我不得不手动放置它所以该函数在字符串之外不起作用好的代码:

    string temp;
list<string>::iterator it;
it=mylist.begin();//let's say myslist has "random stuff"
temp=*it;//this does not copy the '\0'
temp+='\0';//so i add it myself
for(int n(0);temp[n]!='\0';n++)//now the for loop stops properly
cout<<temp[n];

最佳答案

如果你想要字符串中的字符:

for (std::string::iterator it=mystr.begin(); it!=mystr.end(); it++)
{
char ch = *it;
// do something with the character?
}

如果要将字符串作为 C(零终止)字符串传递,请使用

mystr.c_str()

关于c++ - 将元素从 list<string>mylist 复制到字符串 mystr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7408049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com