c++ - 如何将 std::string 用于 char* 输出参数

标签 c++ parameters stdstring

对于声明为采用 char* output 参数的任何函数,是否可以将 s std::string 的“char”部分指定为函数的输出?

我开始于:

// EDIT:  ADDED THESE TWO LINES FOR CLARITY

sprintf(buf, "top -n 1 -p %s" , commaSeparatedListOfPIDs.c_str() );
fp = popen(buf, "r");

std::string  replyStr;
char         reply[100];

rc = scanf( fp, "%s", reply );
replyStr = reply;

但这似乎有点笨拙。

那么,有没有办法说:

rc = scanf( fp, "%s", &replyStr.c_str() );

或者类似的东西?

谢谢!

最佳答案

是的,这是可能的:

std::string  replyStr(100, '\0');
//Requires C++11 (to guarantee that strings hold their characters
//in contiguous memory), and some way to ensure that the string in the file
//is less than 100 characters long.
rc = fscanf( fp, "%s", &reply.front() );
replyStr.erase(replyStr.find('\0'));

第二个条件很难满足,如果不满足,这个程序就有未定义的行为。

关于c++ - 如何将 std::string 用于 char* 输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10325174/

相关文章:

c++ - C++ std::string 的长度(以字节为单位)

C++ 数组输入和退出验证

c++ - 自定义 wxWidgets 小部件中彼此相邻的两个按钮

C++ - 将文件处理程序传递给打开函数时出错

c++ - QString 到 const byte* 转换

ruby-on-rails - Rails 5.1 - 允许使用 JSON 参数,但在日志中仍显示为未经允许

powershell - 使用参数 ("By Reference"参数从 PowerShell 返回对象)?

c++ - std::string 连接操作

c++ - 交换 std::vector 作为函数参数

c++ - basic_string<CharT> 与 CharT*