我有一个函数可以打印连接到服务器的所有客户端。我想将所有客户端放在一个 char 列表(list lst)中,因为我在其他函数中需要它们。当我想遍历列表 lst 和打印元素看起来像“$@”。我不明白为什么。 这些是函数:
void get_clients_list(){
int dim,i = 0,n;
char buff[255];
bzero(buff,sizeof(buff));
recv(srv_fd,buff,sizeof(buff),0);
dim = atoi(buff);
printf("\t%d clients available:", dim);
printf("\n");
while(i < dim){
memset(buff, 0, sizeof(buff));
recv(srv_fd, buff, sizeof(buff),0);
if(n < 0){
error("ERROR reading from socket");
}
lst.push_back(buff);
printf("\t\t%s", buff);
printf("\n");
i++;
}
}
下面是我如何遍历列表 lst:
get_clients_list();
iter = lst.begin();
while(iter != lst.end()) {
iter ++;
printf("clients:");
printf("%s \n",iter);
}
为什么不打印客户端,只出现一些象形文字?
最佳答案
您在这里添加了一个指向局部变量的指针:
lst.push_back(buff);
这是未定义的行为。您还需要使用 *iter
来获取迭代器的内容:
printf("%s \n",*iter);
由于您使用的是 C++,因此使用 std::string
和 iostream
库会更简单且更不容易出错。尽可能贴近您在此处的代码是一个小示例:
#include <string>
#include <vector>
#include <iostream>
int main()
{
char buff[] = "hello, world" ;
std::vector<std::string> lst;
lst.push_back( buff ) ;
std::vector<std::string>::iterator iter = lst.begin() ;
// In C++11 could be replaced with
//auto iter = lst.begin() ;
while( iter != lst.end() )
{
std::cout << *iter << std::endl ;
++iter ;
}
}
关于c++ - C++ 中的 char* 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16441009/