Reputation: 35
this is my first time posting a question so I hope I'm getting this right. Anyways, I'm trying to create a program to ask the user for a string, count the types and numbers of letters, then output the frequency of the letters. So far I'm having an error with even getting the right input, and just can't figure out what the issue is. My (relevant) code is:
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
string getPhrase(const string & phrase); //Function for gathering string input
int main()
{
const string phrase;
getPhrase(phrase);
...
}
string getPhrase(const string &phrase)
{
cout<<"Enter phrase: "
getline(cin, phrase);
return (phrase);
}
When I run, this I get the error:
freq.cpp: In function ‘std::string getPhrase(const std::string&)’:
freq.cpp:21: error: no matching function for call to ‘getline(std::istream&, const
std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)’
I have no idea what I'm doing wrong, and just can't seem to find anything online that's relevant to what I'm doing.
Upvotes: 0
Views: 1784
Reputation: 110648
Notice that phrase
is a const string
. That means it's constant and can't be modified. Therefore you can't use getline
to set phrase
to the user's input.
You should declare phrase
with string phrase;
and then make the parameter of getPhrase
a non-const
reference.
string getPhrase(string& phrase); //Function for gathering string input
int main()
{
string phrase;
getPhrase(phrase);
...
}
Upvotes: 0
Reputation: 476950
Your getPhrase
should look like this:
std::string getPhrase()
{
std::string result;
std::cout << "Enter phrase: ";
std::getline(std::cin, result);
return result;
}
Then:
int main()
{
std::string phrase = getPhrase();
// ...
}
Upvotes: 1
Reputation: 23624
const string phrase;
remove const
in function parameter and local variable declaration since otherwise you can't accept user input to a const
variable, which means nonchangable/ non-modifiable.
Like the following:
string getPhrase(string & phrase); //Function for gathering string input
int main()
{
string phrase;
getPhrase(phrase);
//...
}
Upvotes: 0