-1
#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?

  • 8
    Stop using `gets` immediately, it has been removed from the language because it has no bounds checking. – Barmar Jan 19 '23 at 18:35
  • 4
    `a` (and `i`) goes out of scope when the `for` loop ends. Declare `int a = 0;` _before_ the `for` loop if you need it _after_ the `for` loop – Ted Lyngmo Jan 19 '23 at 18:35
  • 1
    The scope of the variable is the loop body. You can't access it outside. – Barmar Jan 19 '23 at 18:35
  • ... and as @Barmar mentioned: Never use `gets`. Use `fgets(input, sizeof input, stdin);` instead (and check the return value). – Ted Lyngmo Jan 19 '23 at 18:37
  • 1
    I suggest that you read this: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/12149471) – Andreas Wenzel Jan 19 '23 at 20:55
  • `if (!fgets (input, sizeof input, stdin) { return 1; } input[strcspn (input, "\n")] = 0;` is your replacement for `gets()` that also trims the `'\n'` from the end of `input` by overwriting with the null-byte. – David C. Rankin Jan 20 '23 at 06:16
  • What type is 'a'? – Martin James Jan 20 '23 at 09:33

2 Answers2

2

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?

Harith
  • 4,663
  • 1
  • 5
  • 20
1

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++ )
  ...
John Bode
  • 119,563
  • 19
  • 122
  • 198