什么是C ++成语替换snprintf(3)? [英] What is the C++ idiom to replace snprintf(3)?
问题描述
我有一些C ++代码,当解析某个文件头失败时需要生成错误消息。在这种情况下,我需要确保头中的某个4字节字段是OggS,如果不是,则返回错误消息,如invalid capture_pattern:'FooB'; expecting'OggS'。我的代码看起来像这样:
const string OggPage :: parseHeader(void){
read(fd,capture_pattern ,sizeof(capture_pattern)); //错误处理省略
if(strncmp(capture_pattern,CAPTURE_PATTERN,sizeof(capture_pattern))!= 0){
char err [256]
snprintf(err,sizeof(err),无法从文件描述符%d读取%d个字节%s:\\ n,sizeof(capture_pattern),fd,err);
return err;
}
return一切都很好!
}
从其他数据类型构建字符串的标准C ++语言是什么?我不像这里的 printf(3)
- 样式格式,所以随意建议任何工作。
istream
部分不会被使用) ostringstream
更合适。 #include< sstream>
#include< string>
#include< iostream>
int main(){
std :: stringstream str_stream;
int number = 5;
str_stream<< String with number<<数字<< std :: endl ;;
std :: string str = str_stream.str();
std :: cout<< str;
}
I have some C++ code which needs to generate an error message when parsing a certain file header fails. In this case, I need to ensure that a certain 4 byte field in the header is "OggS", and if it is not, return an error message like "invalid capture_pattern: 'FooB'; expecting 'OggS'". My code looks something like this:
const string OggPage::parseHeader(void) {
read(fd, capture_pattern, sizeof(capture_pattern)); // error handling omitted
if (strncmp(capture_pattern, CAPTURE_PATTERN, sizeof(capture_pattern)) != 0) {
char err[256];
snprintf(err, sizeof(err), "Failed to read %d bytes from file descriptor %d: %s\n", sizeof(capture_pattern), fd, err);
return err;
}
return "Everything was A-OK!";
}
What is the standard C++ idiom for building a string from other datatypes? I'm not wedded to the printf(3)
-style format here, so feel free to suggest anything that works.
You can use stringstream
or ostringstream
from C++ Standard library. If further stream will not be used to read values from it (e.g. it's istream
part won't be used) ostringstream
is more suitable.
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::stringstream str_stream;
int number = 5;
str_stream << " String with number " << number << std::endl;;
std::string str = str_stream.str();
std::cout << str;
}
这篇关于什么是C ++成语替换snprintf(3)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!