在C++中从FILE结构解析为字符串

Parse from FILE structure to string in C++

本文关键字:字符串 结构 C++ 中从 FILE      更新时间:2023-10-16

我正试图用以下代码在Windows上捕获一个系统命令,以字符串形式返回输出。

std::string exec(char* cmd) {
FILE* pipe = _popen(cmd, "r");
if (!pipe) return "ERROR";
std::ifstream ifs(pipe);
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>()    ) );
printf("%s", content);
return content;
}

当我调用这样的函数时:

char *command = "set";
std::string results = exec(command);
printf("%s", results);
getchar();

输出只是几个随机字节。

╝÷:ö°:

我试图将所有结果附加在一个长字符串中。有人能告诉我我做错了什么吗?我尝试用命令将stderr重定向到输出,但它也提供了一些随机字节。

由于您使用的printf()对C++std::string值一无所知,因此需要打印content:的C字符串表示

printf("%s", content.c_str());

printf()函数被告知要预料到这一点,但它并不是你传递给它的

或者,正如其他人所指出的,您应该使用本机C++I/O:

std::cout << content;

Printf需要C字符串char*

使用

printf("%s",results.c_str());

不要使用printf,而是使用C++标准输出流:

std::cout << content << 'n';