cin.get(a, 256);
for(int i = 0; i < strlen(a); i++){
if(strchr("aeiou", a[i])){
s = 0;
strcpy(substr, empty);
isubstr = 0;
}
else{
s++;
substr[isubstr++] = a[i];
if(s > maax || s == maax){
maax = s;
memset(show, 0, 256);
strcpy(show, substr);
}
}
}
cout << show;
This is the code. It intends to find the longest substring with only consonants and if there are 2+ with the same lenght it outputs the farthest one (closer to the right)
Consider the following sequence:
jfoapwjfppawefjdsjkflwea
Splitted by vowels it wold look something like this:
jf |oa| pwjfpp |a| w |e| fjdsjkflw |ea|
Notice how "fjdsjkflw" is the largest substring without a vowel. This code outputs just that including some random numbers at the end:
fjdsjkflwê²a
Why does this happen? Why does it put NULL 3 characters beyond of what it's intended to?
For starters you should write a function that finds such a longest sequence of consonants.
You provided an incomplete code so it is difficult to analyze it. For example it is not seen where and how variables substr
and empty
used in this call
strcpy(substr, empty);
are defined and what are their meanings.
Also there are statements like this
memset(show, 0, 256);
that do not make a sense because for example after this statement there is the statement
strcpy(show, substr);
So the previous statement is just redundant.
Or for example it seems that one of these variables s
and isubstr
is also redundant.
I can suggest the following solution implemented as a function.
#include <iostream>
#include <utility>
#include <cstring>
std::pair<const char *, size_t> max_consonant_seq( const char *s )
{
const char *vowels = "aeiouAEIOU";
std::pair<const char *, size_t> p( nullptr, 0 );
do
{
size_t n = std::strcspn( s, vowels );
if ( n != 0 && !( n < p.second ) )
{
p.first = s;
p.second = n;
}
s += n;
s += std::strspn( s, vowels );
} while ( *s );
return p;
}
int main()
{
const char *s = "jfoapwjfppawefjdsjkflwea";
auto p = max_consonant_seq( s );
if ( p.second ) std::cout.write( p.first, p.second ) << '\n';
return 0;
}
The program output is
fjdsjkflw
The function returns a pair of objects. The first one specifies the starting pointer of the maximum sequence of consonants in the passed string and the second object specifies the length of the sequence.
All what you need to understand how the function works is to read the description of the two C string functions strspn
and strcspn
.