在 c_str)、length() 和 size() 之间发现不连贯

Incoherence found between c_str(), length() and size()

本文关键字:size 之间 不连贯 发现 length str      更新时间:2023-10-16

我正在使用 std::unordered_map 数据结构从文本文件构建地图,使用 。BaseDevice 是一个结构,包含一个 64 位 id 和一个字符串:

struct BaseDevice
{
public:
    uint64_t id;
    string ipAddress;
}

我读取了一个文件(假设它被正确写入)并按如下方式构建地图:

char buffer[1024];
ifstream fin(myfile.c_str());
while(fin.eof() == false)
{
  fin.getline(buffer, 1023);
  StringTokenizer st(buffer, " ");
  //Parse ID and address
  unsigned int id = atoi(st.nextToken().c_str()); //get ID
  string ipAddress = st.nextToken();  //get IP address
  //Create the local structure and add to the map
  BaseDevice dev;
  dev.id = id;
  dev.ipAddress = ipAddress;
  myMap[id] = dev;
  break;
}

奇怪的是,当我遍历地图时,ipAddress 字符串似乎是 (null),而 length() 和 size() 都不是。

unordered_map< string, BaseDevice >::const_iterator itr1;
for(itr1 = myMap.begin(); itr1 != myMap.end(); itr1++)
{
  const BaseDevice& device = itr1->second;
  fprintf(stdout, "id %lu ipAddress %s n", myMap->first, device.ipAddress);
  printf("Length is %d n", device.ipAddress.length());
  printf("Size is %d n", device.ipAddress.size());
  /*
  OUTPUT:
  id 2 ipAddress (null)
  Length is 8  
  Size is 8
  */
}

我想问你:这怎么可能?我做错了什么吗?谢谢。

您正在打印device.ipAddress,就好像它是 C 字符串(带有%s格式说明符)一样,这是不正确的,因此fprintf尝试打印它时可能会发疯。你应该做:

fprintf(stdout, "...%s...", device.ipAddress.c_str());

您也可以对std::cout执行相同的操作:

std::cout << device.ipAddress << 'n';