对于声明为采用 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/