Re: Black magic when using fopen!?
A somewhat refined / improved version of the facilities suggested so
far by other posters, used to trim strings at the NULL character and
to inspect them, in general:
-------
#include <iostream>
#include <string>
#include <sstream>
#include <limits>
#include <iomanip>
void trim_c_str(std::string* str) {
size_t pos = str->find('\0');
if (pos != std::string::npos) str->erase(pos);
}
void dump_as_unsigned(std::ostream& os,
const std::string& str,
size_t w = 0,
const std::string& lead_sep = " ") {
for (size_t i = 0, e = str.size(); i < e; ++i) {
os << lead_sep << std::setw(w) << unsigned(str[i]);
}
os << std::endl;
}
void dump_chars(std::ostream& os, const std::string& str, size_t
spaces = 0) {
if (spaces) {
for (size_t i = 0, e = str.size(); i < e; ++i) {
os << std::string(spaces, ' ') << str[i];
}
} else {
os << str;
}
os << std::endl;
}
std::string string_details(const std::string& str) {
static std::ostringstream oss;
static size_t w = 0;
if (!w) {
oss << std::hex << unsigned(std::numeric_limits<char>::max());
oss << std::setfill('0') << std::uppercase;
w = oss.str().size();
}
oss.str("");
oss << "---" << std::endl;
oss << "As string:" << std::endl;
oss << " \"" << str << "\", ";
oss << str.size() << " chars" << std::endl;
dump_chars(oss, str, w);
dump_as_unsigned(oss, str, w);
std::string c_str = str.c_str();
if (c_str != str) {
oss << std::endl;
oss << "As c_str():" << std::endl;
oss << " \"" << c_str << "\", ";
oss << c_str.size() << " chars" << std::endl;
dump_chars(oss, c_str, w);
dump_as_unsigned(oss, c_str, w);
} else {
oss << "[ string == c_str(), no NULL characters ]";
oss << std::endl;
}
oss << "---" << std::endl;
return oss.str();
}
int main() {
std::string s = std::string("Here ->") + '\0' + "<- is NULL";
std::cout << "Before trimming:" << std::endl;
std::cout << string_details(s) << std::endl;
trim_c_str(&s);
std::cout << "After trimming:" << std::endl;
std::cout << string_details(s) << std::endl;
}
-------
Output:
-------
Before trimming:
---
As string:
"Here -> <- is NULL", 12 chars
H e r e - > < - i s N U L L
48 65 72 65 20 2D 3E 00 3C 2D 20 69 73 20 4E 55 4C 4C
As c_str():
"Here ->", 7 chars
H e r e - >
48 65 72 65 20 2D 3E
---
After trimming:
---
As string:
"Here ->", 7 chars
H e r e - >
48 65 72 65 20 2D 3E
[ string == c_str(), no NULL characters ]
---
-------
[ posted for portability sake, too ]
--
Francesco S. Carta, http://fscode.altervista.org
First time here? Read the 'Welcome' and the 'FAQ'
Welcome: http://www.slack.net/~shiva/welcome.txt
C++ FAQ: http://www.parashift.com/c++-faq-lite