Matija Mitrović
Matija Mitrović

Reputation: 23

gets() and puts() showing characters that i did not enter

So I got the task to make program that will take input until I write "KRAJ". But when I print it with puts() it will have 3 chars more in first 3 places. Let's say I write "finish meKRAJ" it would have to print only "finish me" but it prints "ć[]'finish me"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char text[100];
    char entry[100];
    int i;
    int flag=1;
    int flag2;
    do{
        printf("Enter txt:finish by writing KRAJ\n");
        gets(entry);
        for(i=0;i<strlen(entry);i++){
            if(entry[i] == 'K' && entry[i+1] == 'R' && entry[i+2] == 'A' && entry[i+3] == 'J'){
                strncat(text,entry,i);
                flag=0;
                flag2=1;
                break;
            }
            else{
                flag2=0;
            }
        }
    if(!flag2)strcat(text,entry);
    }while(flag);

    printf("\n You have entered:\n");
    puts(text);
    //testing first char

    printf("\nTesting first char:%c",text[0]);
    printf("\ntxt lenght:%d",strlen(text));


return 0;
}

Upvotes: 0

Views: 80

Answers (1)

Andrew Henle
Andrew Henle

Reputation: 1

Let's say I write "finish meKRAJ" it would have to print only "finish me" but it prints "ć[]'finish me"

char text[100];

is never initialized, yet you call

strncat(text,entry,i);

and

if(!flag2)strcat(text,entry);

Those two calls will append your strings to whatever garbage is in text[100] when your program starts.

Upvotes: 3

Related Questions