rv.
rv.

Reputation: 81

Unexpected output from simple C program

This code basically returns an unique string. So, the resultant string only has unique characters.

Input: "This is an example input" Output: "this anexmpl" . But i should be getting a 'u' as well. It was working fine with other IDEs. I just downloaded devcpp 4.9.9.2 and I am using it as an IDE. The code works fine.

#include<stdio.h>
#include<conio.h>
#include<string.h>
int search(char result[30],char temp)
{
    for(int i=0;result[i];i++){
        if(temp == result[i])
            return 0;
    }
    return 1;
}
int main()
{
    char str[20];
    printf("\nEnter String: ");
    gets(str);
    //scanf("%[^\t\n]s",str);
    //strlwr(str);
    for(int i=0;i<strlen(str);i++){
      if(str[i]>=65 && str[i]<=90)
             str[i]=str[i]+32;
    }
    int length=0;
    for(int i=0;str[i];i++)
        length++;
    char result[30];
    result[0]='\0';
    int ctr=0;
    for(int j=0;str[j];j++){
        if(search(result,str[j]) == 1){
            printf("%c\t",str[j]);
            result[ctr]=str[j];
            ctr++;
        }
    }
    result[ctr]='\0';
    printf("\nUnique String:");
    printf("\n%s\n",result);
    char reverse[20];
    int reslength=0;
    for(int k=0;result[k];k++)
        reslength++;
    int counter=0;
    printf("Reversed String:\n");
    for(int t=reslength-1;t>=0;t--){
        printf("%c",result[t]);
    }
    getch();
    return 0;
}

Upvotes: 0

Views: 80

Answers (1)

Paul R
Paul R

Reputation: 212929

One immediate problem is that str is too small at 20 chars - your input string is much larger than this, so you have a buffer overflow and therefore undefined behaviour. Change:

char str[20];

to, e.g.:

char str[256];

Also: never use gets - use fgets instead. Change:

gets(str);

to:

fgets(str, sizeof(str), stdin);

That way you can't get buffer overflows if the input string is too long.


One further point on programming style - never use hard-coded ASCII constants for characters - it's pointless, non-portable and difficult to read/maintain - so change, e.g.:

  if(str[i]>=65 && str[i]<=90)
      str[i]=str[i]+32;

to:

  if(str[i]>='A' && str[i]<='Z')
      str[i]=str[i]-'A'+'a';

or better still, use <cytpes.h> and get rid of the above two lines with just:

str[i] = tolower(str[i]);

And a final word of advice: always enable compiler warnings and take heed of them - your code generates several warnings, none of which happen to be serious in this instance, e.g.:

main.c:39:10: warning: unused variable 'reverse' [-Wunused-variable]
     char reverse[20];
          ^
main.c:43:9: warning: unused variable 'counter' [-Wunused-variable]
     int counter=0;
         ^

Always fix compiler warnings though, even if they don't appear to be problematic at first sight - one day this could save your life (or at least your job).

Upvotes: 3

Related Questions