I'm currently solving problems for my high school final exam at programming in C . I tried solving a problem in CodeBlocks, but it gives me this error at line 13:
error: invalid conversion from 'const char*' to 'int' [-fpermissive]
I don't see what is wrong.
The problem is about removing the last consonant from a string. The string is "mare frig saci"
and it should produce "mare frig sai"
, removing the last 'c'
.
Here is my code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s[256];
int i;
cin.get(s,256);
for(i=strlen(s)-1;i=0;i--)
{
if(strchr(s,"aeiou")!=0)
strcpy(s i 1,s i-1);
}
cout<<s;
return 0;
}
CodePudding user response:
There are a few problems:
i=0
is not a condition, it's an assignment.i>=0
is probably what you're looking for herestrchr
take in astring
andchar
(1), and return a pointer (2), not anint
to be compared. Both (1) and (2) condition isn't sastified. In any case,strchr
is not ideal to use here.
I recommended using std::string
(as it's more easy to use and standard in C ) and std::string::find_last_of
, which find the last character in string inside a set of characters, exactly what you wanted here:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s; getline(std::cin, s);
string cons = "bcdfghjklmnpqrstvwxyz";
size_t pos = s.find_last_of(cons);
if (pos != string::npos) //if a consonant is found
{
s.erase(pos, 1);
}
cout << s;
}
CodePudding user response:
std::strchr
- The valid signatures are
So, you are supplying it with the wrong things.const char* strchr( const char* str, int ch ); char* strchr( char* str, int ch );
std::strcpy
- "The behavior is undefined if the strings overlap" - so you can't usestd::strcpy
to move the end of the string to the new place. Instead usestd::memmove
.- Since the string you mention contains a space at the end, you must add space to the list of vowels.
- You assign
0
toi
instead of checking it's value.
Example:
#include <cstring>
#include <iostream>
int main() {
char s[256] = " mare frig saci ";
for (size_t len = strlen(s), i = len; i-- > 0;) { // corrected loop
if (std::strchr("aeiou ", s[i]) == nullptr) { // corrected check
std::memmove(s i, s i 1, len - i); // corrected move
break; // and break out
}
}
std::cout << s << '\n';
}