【问题标题】:getline: template argument deduction/substitution failedgetline:模板参数扣除/替换失败
【发布时间】:2014-12-10 21:20:49
【问题描述】:

当我尝试逐行读取命令行的输出时出现此错误:

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

注意:模板参数扣除/替换失败:注意:
'std::string {aka std::basic_string}' 不是从 'std::basic_istream<_chart _traits>' 执行(命令),行

【问题讨论】:

    标签: c++


    【解决方案1】:

    为了解决错误消息的原因,我猜它来自std::getline()getline 需要 std::istream 作为其第一个参数。如果你想从output阅读,你可以使用std::stringstream

    std::stringstream ss(output);
    while (std::getline(ss, line)) {
        /* ... */
    }
    

    【讨论】:

      【解决方案2】:
      std::getline(output, line)
      

      你试图用两个字符串调用 getline,这是错误的,它需要一个 istream 和一个字符串。

      要使用 getline,您需要将输出放入流中:

      std::istringstream outstr(output);
      getline(outstr, line);
      

      【讨论】:

      • 谢谢,它说“outstr 有初始化程序但类型不完整”,这意味着它需要 = NULL?
      • 不,这意味着您需要 #include &lt;sstream&gt; 这是定义 std::istringstream 的标头
      猜你喜欢
      • 2013-06-20
      • 2019-09-11
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      相关资源
      最近更新 更多