1

I would like to have my application take either a parameter or read from stdin, and print that on the screen. But I'm having problems when trying to concatenate the strings.

I found out that "+" would do, but it's giving me problems so I attempted to use the append method which is now throwing the error I'm showing below.

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

Input:

enter image description here

Error:

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)
default
  • 11,485
  • 9
  • 66
  • 102
Matias Barrios
  • 4,674
  • 3
  • 22
  • 49

2 Answers2

1

endl is a modifier for output streams that prints a newline then flushes the stream. If you want to append a newline to a string, you should append "\n".

Besides, you are missing the return statement from your function.

petersohn
  • 11,292
  • 13
  • 61
  • 98
1

Simply change:

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

To:

result += input_line + '\n';

Note that you have more issues here:

  • You are missing a return statement
  • You will never stop reading input naturally, only CTRL+D terminates it (on Mac...)
Daniel Trugman
  • 8,186
  • 20
  • 41