#include <stdio.h>
#include <string.h>
int main()
{
char input[100], output[100];
gets(input);
for(int i=0, a=0; i<strlen(input); a )
{
char word = input[i];
output[a] = word;
if(word == 'a' || word == 'e' || word == 'i' || word == 'o' || word == 'u') i =3;
else i =1;
}
output[a] = '\0';
puts(output);
}
It says a is not declared, but didn't i declare it in the loop? How to declare a variable inside a loop without getting an error?
CodePudding user response:
Local scope :
In
for(int i=0, a=0; i<strlen(input); a )
a
goes out of scope, or is destroyed, once the loop exits.
From C11:
For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.
Fix:
Declare a
outside the loop.
Using gets():
The function gets()
is inherently dangerous, and has been removed from the C standard. It provides no bounds checking and can potentially cause a buffer overflow.
Instead, use fgets
.
See: Why is the gets function so dangerous that it should not be used?
CodePudding user response:
You're getting that error because you're using a
outside the body of the loop:
output[a] = '\0';
a
is only visible within the body of the for
loop, and once the loop exits it no longer exists.
The easy way to deal with it is to declare a
before the loop:
int a = 0;
for ( int i = 0; i < strlen( input ); a )
...