【问题标题】:c++ read stdin from heredocc++ 从heredoc 读取标准输入
【发布时间】:2012-08-26 20:05:19
【问题描述】:

如果我有我的命令行,例如:

foo arg1 arg2 << HEREDOC
  line1
  line2
HEREDOC

在 foo 中,我如何从 heredoc 中获取价值?

int main( char *argv[] )
{
  string arg1=argv[1];
  string arg2=argv[2];

  string heredoc= ?
}

【问题讨论】:

    标签: c++ stream std


    【解决方案1】:

    heredoc 只是将内容重定向到stdin。所以你可以使用:

    string str;
    while (getline(cin, str))
        cout << str << endl;
    

    【讨论】:

    • 我收到Terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct NULL not valid
    • @francoisrv 这可能是因为您的 main 声明不正确。它必须是int main(int argc, char *argv[])。 (不过还有其他正确的声明)
    • 是的,现在可以使用 #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;string&gt; using namespace std; int main( int argc, char *argv[] ){ string db = argv[1]; string str; string query; while (getline(cin, str)) query=query + str; cout &lt;&lt; query; return 1; }
    【解决方案2】:

    这里的文档是另一种进行 IO 重定向的方法。 您的 shell 命令基本上是将行 line1 然后 line2 放入程序的 stdin 中。

    所以你的代码应该是这样的:

    int main(int argc, char *argv[])
    // notice that your main declaration isn't conforming to C++ standard.
    // it need additional argc parameter
    {
      string arg1=argv[1];
      string arg2=argv[2];
    
      string heredoc_string1, heredoc_string2;
      getline(cin, heredoc_string1); 
      getline(cin, heredoc_string2);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2012-02-17
      • 2015-05-28
      • 1970-01-01
      相关资源
      最近更新 更多