用C ++读取stdin并在字符串内连接

时间:2017-10-17 14:27:33

标签: c++ string parameters concatenation

我想让我的应用程序接受参数或从stdin读取,并在屏幕上打印。但是在尝试连接字符串时我遇到了问题。

我发现“+”会这样做,但是它给了我一些问题,所以我试图使用append方法,现在抛出我在下面显示的错误。

#include <iostream>
using namespace std;

std::string Read_stdin(){
    std::string result="";
    std::string input_line="";
    while(cin) {
        getline(cin, input_line);
        result.append(input_line).append(endl);
    };
}


int main(int argc, char** argv)
{
    std::string input = (argc == 2) ? argv[1] : Read_stdin();
    cout << "Your input is : " << input;
    return 0;
}

输入:

enter image description here

错误:

jdoodle.cpp: In function 'std::__cxx11::string Read_stdin()':
jdoodle.cpp:13:46: error: no matching function for call to 'std::__cxx11::basic_string<char>::append(<unresolved overloaded function type>)'
         result.append(input_line).append(endl);
                                              ^
In file included from /usr/include/c++/5.3.0/string:52:0,
                 from /usr/include/c++/5.3.0/bits/locale_classes.h:40,
                 from /usr/include/c++/5.3.0/bits/ios_base.h:41,
                 from /usr/include/c++/5.3.0/ios:42,
                 from /usr/include/c++/5.3.0/ostream:38,
                 from /usr/include/c++/5.3.0/iostream:39,
                 from jdoodle.cpp:1:
/usr/include/c++/5.3.0/bits/basic_string.h:983:7: note: candidate: std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::append(const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]
       append(const basic_string& __str)

2 个答案:

答案 0 :(得分:1)

endl是输出流的修饰符,用于打印换行符然后刷新流。如果要在字符串中附加换行符,则应附加"\n"

此外,您缺少函数的return语句。

答案 1 :(得分:1)

简单地改变:

result.append(input_line).append(endl);

要:

result += input_line + '\n';

请注意,您在此处遇到更多问题:

  • 您缺少退货声明
  • 你永远不会自然地停止阅读输入,只有CTRL + D终止它(在Mac上......)