I've seen a similar post on StackOverflow about this error code, but theirs seemed to have an error code line, and they were also attempting something slightly different in their function.
I'm trying to count the number of a specified character in a string (inputting p
and apple
would return 2, for example). At some point, my method broke down. I've been scouring my code for what specific increment operator is causing this, but without an error code line I don't know which one is causing it, and I've messed around with both.
I'm not sure which of these variables isn't modifiable, but all it tells me is:
main.cpp:11:30: error: lvalue required as increment operand
If anyone could take a look at my code and tell me what's wrong, I would really appreciate it.
#include <iostream>
#include <string>
using namespace std;
int main() {
string b;
char a;
int i;
int counter(string b) {
counter = 0;
for(int i = 0; i < b.length(); i )
if (b[a] == a), counter );
counter = i;
return counter;
}
cin >> a;
cin >> b;
return counter(b);
}
return 0;
}
PS, I know this code has multiple other errors. It's a work in progress, but I am trying to focus on this operand issue first.
I've been trying to redefine variables for both counter
and i
, as I'm not sure which one is causing the issue, but nothing has fixed it. For example, within the for
loop, I tried setting counter
equal to some variable, but that didn't help. I think it's possible I messed up the syntax too within the for
loop, and I spent some time in there, but if that's the issue I didn't fix it.
CodePudding user response:
The program is invalid
In this line
int counter(string b); {
^^^
you declared a function with the name counter
(see the semicolon).
After the function declaration there is followed a compound statement
int counter(string b); {
counter = 0;
for(int i = 0; i < b.length(); i )
if (b[a] == a), `counter `);
return counter;
}
within which the function name counter
is used as a variable as for example counter
So the compiler issues the error message
"main.cpp:11:30: error: lvalue required as increment operand".
because you are using the function name and trying to apply to it the post-increment operator . But the function designator in this case in implicitly converted to a pointer to the function and it is not an lavlue.
After the compound statement you are calling the function counter though it is not defined
return counter(b);
It seems you are trying to define the function counter
within the function main
. You may not do that.
Also the function should accept two arguments: the string and the character.
Your program can look the following way
#include <iostream>
#include <string>
size_t counter( const std::string &s, char c )
{
size_t count = 0;
for ( char ch : s )
{
if ( c == ch ) count;
}
return count;
}
int main()
{
std::string s;
char c;
std::cin >> s;
std::cin >> c;
std::cout << counter( s, c ) << '\n';
}