2

I have looked at a few other questions regarding getline() not functioning, however most problems regarding the topic were due to the programmer not including the string header. I have the string header included however getline is still giving me error E0304 (which I have already looked into).

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    char input[100];
    getline(cin, input);
    cout << input << endl;
}
William
  • 29
  • 3
  • Also, please avoid `std::endl` when `\n` suffices. `std::endl` flushes the buffer, while `\n` does not. Unnecessary flushing can cause performance degradation. See [`std::endl` vs `\n`](https://stackoverflow.com/q/213907/9716597). – L. F. Jul 27 '19 at 03:34
  • I for one have not spent time memorizing error codes. What is error E0304? The exact, full error message would be much more useful than just the error code. – JaMiT Jul 27 '19 at 04:26

2 Answers2

1

There are two forms of getline:

std::cin.getline(array, size); // reads into raw character array
getline(std::cin, string);     // reads into std::string

You should use a std::string instead of a raw character array:

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    std::string input;
    getline(std::cin, input);
    std::cout << input << "\n";
}
L. F.
  • 19,445
  • 8
  • 48
  • 82
0

The non-member getline only works with std::string. Use the std::istream member function getline for C-style strings:

std::cin.getline(input, sizeof(input));
O'Neil
  • 3,790
  • 4
  • 16
  • 30
eesiraed
  • 4,626
  • 4
  • 16
  • 34