c++ - C++ 中的 char* 列表

标签 c++ list char

我有一个函数可以打印连接到服务器的所有客户端。我想将所有客户端放在一个 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::stringiostream 库会更简单且更不容易出错。尽可能贴近您在此处的代码是一个小示例:

#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/

相关文章:

c - while循环中的哪条语句会先执行?

c - 显示指针减法

c++ - macOS 上的 .so 和 .dylib 有什么区别?

c++ - 扩展 SWIG 内置类

c++ - 字符串数组,我该如何使用它?执行

python - 调用类内部的函数来设置列表的元素

python - 使用列表 if 语句填充字典

python - 获取列表中相邻元素的所有组合

c++ - 从模板函数调用的模板类的模板成员函数

java - 如何清除单个字符串的不同部分,同时使结果成为字符串本身?