getline: template argument deduction/substitution failed

匿名 (未验证) 提交于 2019-12-03 01:44:01

问题:

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

回答1:

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);


回答2:

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)) {     /* ... */ }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!