Search code examples
cstringstdoutstdin

My c program is generating an unwanted output


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
int main()
{
    system("cls");
    int i1,n;
    scanf("%d\n",&n);
    for(i1=0;i1<n;i1++)
    {
        char *s;
        s=(char *)malloc(sizeof(char)*20);
        gets(s);
        int l=strlen(s);
        int l1=l;
        int i,j;
        for(i=0;i<l;i++)
        {
            if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='O'||s[i]=='I'||s[i]=='U')
            {
                for(j=l1-1;j>=0;j--)
                {
                    if(s[j]=='a'||s[j]=='e'||s[j]=='i'||s[j]=='o'||s[j]=='u'||s[j]=='A'||s[j]=='E'||s[j]=='O'||s[j]=='I'||s[j]=='U')
                    {
                        printf("%c",s[j]);
                        l1=j;
                        break;
                    }
                }
            } 
            else
            {
            printf("%c",s[i]);
            }
        }
        printf("\n");
        free(s);
    }
    getch();
    return 0;
}

it's a program to reverse the order of the vowels of a string (education -> odicatuen). In the image below the left one is input file & right one is output file. You can see there is an upper arrow at the beginning

left one is input file & right one is output file

There is no bug in the program. It works fine. I have an input text file & I'm saving my output in an output text file via command prompt. I am getting an unexpected "upper arrow character" at the beginning of my output file


Solution

  • The problem is caused by the call to system("cls");

    The cls command clears the console screen. This is done by printing a form feed character (ASCII value 12) to stdout. A command prompt interprets this character as clearing the screen. But when you redirect output to a file, this character becomes part of the output. So the up-arrow character you're seeing is how ASCII code 12 is being displayed in Notepad.

    Remove the call to system("cls"); and you won't get the extra output in the file.