I'm getting this error when I try to read the output of a command line by line:
std::string exec(const char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "";
char buffer[128];
std::string result = "";
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL) {
result += buffer;
}
}
pclose(pipe);
return result;
}
string commandStr = "echo Hello World";
const char *command = commandStr.c_str();
std::string output = exec(command);
std::string line;
while (std::getline(output, line)) {
send(sockfd, line.c_str(), line.length(), 0);
}
note: template argument deduction/substitution failed: note:
'std::string {aka std::basic_string}' is not derived from 'std::basic_istream<_CharT, _Traits>' exec(command), line <- Error
To solve the cause of the error message, I would guess it is from std::getline()
. getline
requires an std::istream
as its first argument. If you want to read from output
, you can use std::stringstream
std::stringstream ss(output);
while (std::getline(ss, line)) {
/* ... */
}
std::getline(output, line)
You're trying to call getline with two strings, that's wrong, it takes an istream and a string.
To use getline you need to put the output into a stream:
std::istringstream outstr(output);
getline(outstr, line);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.