在 c_str)、length() 和 size() 之间发现不连贯
Incoherence found between c_str(), length() and size()
我正在使用 std::unordered_map 数据结构从文本文件构建地图,使用
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';
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 大于65535的C++数组[size]引发不一致的溢出
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 为什么(-1)%vector::size()总是返回0
- vector.back() 和 vector[vector.size() - 1] 之间的区别?
- .at(vect.size())= x之间的差异;和vect.push_back(x);
- vector.size()= 0和vector.empty()之间是否有区别
- 新的char [size]和新的char [size]()之间的C 差异
- 在 c_str)、length() 和 size() 之间发现不连贯
- std::vector::back 和 vector::operator[ vector::size() - 1] 之间
- size()与图像矩阵行列之间的差异
- push_back()和resize(size()+1)之间有什么区别吗?