Question

I'm working on an assignment for my programming class. One of the given function prototypes is:

string read_text(const string & prompt);

I wrote the function definition as:

string read_text(const string & prompt)
{
    cout << "Enter your text: ";
    getline(cin, prompt);
}

However, this gives me an error:

freq.cpp: In function 'std::string read_text(const std::string&)':
freq.cpp:80: error: no matching function for call to 'getline(std::istream&, const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)'

I read that getline is not supposed to refer to a const variable, so I removed that part, but now I get a Segmentation fault when I run the program.

Was it helpful?

Solution 2

You are missing a return value. Make it:

string read_text()
{
    string prompt
    cout << "Enter your text: ";
    getline(cin, prompt);
    return prompt;
}

Disclaimer: No error checks

OTHER TIPS

It seems you are confusing a compile-time error with a segmentation fault: these are two rather different things. Compile-time errors happen when the code violates language rules. In your case you try to read values into a constant string (const std::string const&). This is clearly not supposed to work. You rather want to use

std::string read_text()
{
    std::string prompt;
    std::cout << "Enter your text: ";
    std::getline(std::cin, prompt);
    return prompt;
}

Given that input has a fair chance to fail, that's probably not a really good idea as it seems this interface unconditionally succeeds.

A segmentation fault, on the other hand, is a run-time error. More specifically, you get a segmentation fault when a piece of memory is accessed which isn't mapped at the accessed location with appropriate access rights. Typically, there is no memory at all mapped at the accessed location. For example, if you try to dereference a null-pointer and write to it you typically get a segmentation fault. Since the behavior of dereference a null-pointer is formally undefined, there is actually no guarantee that anything specific happens.

The code without the const fails to return a value, i.e., there is another form undefined behavior: not returning a value from a non-void function is undefined behavior. The compiler probably injected code which tries to build a std::string from the content of some register or memory location and that doesn't seem to contain a valid pointer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top