在C++中从FILE结构解析为字符串
Parse from FILE structure to string in C++
我正试图用以下代码在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';
相关文章:
- C++结构到字符串
- 从字符串中获取结构的大小
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 如何解析表示树状数据结构的字符串
- 如何将字符串与结构(也包括字符串)进行比较?
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 将字符串存储在 constexpr 结构中
- 为什么我的结构在包含字符串时崩溃?
- 如何将字符串字符与结构数组进行比较?
- 无法使用 strcpy 将字符串复制到静态结构成员
- c++ 将函数参数(带有模板变量的结构)转换为函数体内的字符串
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- C++使用旧编译器GCC 4.4.0在结构列表中查找字符串
- 具有字符串成员的结构的动态数组
- 如何将文本文件保存到C 中的字符串结构
- C++ 斯特劳斯特鲁普的"std_lib_facilities.h"字符串结构 – 警告:无符号表达式的比较
- C++:字符串结构相等
- 返回字符串结构是否安全