0

I'm working on learning C++, and still keep running into stupid problems as I am yet unfamiliar with C++ libraries, and common errors, etc.

right now, the following piece of my code fails:

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

void getInt(int & val){
    string output;
    getline(cin output.c_str());
    val = atoi(output.c_str());
}

and gives me this error when I try to compile it:

test.cpp: In function void getInt(int&):
test.cpp:51: error: expected ) before output
test.cpp:51: error: no matching function for call to getline(std::istream&)

What am I doing wrong? I feel like I'm missing something obvious.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Jonathan
  • 541
  • 4
  • 9
  • 19

3 Answers3

4

It should be

getline(cin, output); // comma, no .c_str()

If you do .c_str(), you're going to invoke undefined behavior when you try to read data into an empty, read only area of memory. That's some bad mojo. Of course, as Lightness points out in the comments, it won't even compile because c_str() is a const char* and getline() needs a char* (non-const) (but even if you did manage to get it to compile, it's important to understand the undefined behavior).

Cornstalks
  • 37,137
  • 18
  • 79
  • 144
3

getline takes two arguments. When passing multiple arguments to a function, you must separate them with a comma. In addition, the second argument can be a std::string, so just pass output directly:

getline(cin, output);
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
2
getline(cin output.c_str());

You forgot a comma, skippy.

Also, your second argument is wrong! The string itself is just called output, and you should only apply .c_str() to it when you need to obtain a C-style character buffer for use with C APIs. i.e. not here.

getline(cin, output);
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055