Why I cannot access the first read char array after reading a series of others in C?

I wanted to read a phrase and a series of numbers/alphabetic separated by ",". I read the first string then I print it (works fine). I read the first string, read 62 of those series and try to print the first string again and is not working. I tried a lot of methods but none working.

    char text[1001];
    scanf("%[^\n]", text);
    for (int i = 1; i <= 62; i++) {
        char alpha[3] = {0}, lit_orig, lit_replace;
        scanf("%s", alpha);
        lit_orig = alpha[0];
        lit_replace = alpha[2];
    }

    printf("\n%s", text);

Input example:

Example text here!
a,H b,j c,6 d,I e,2 f,R g,5 h,t i,h j,k k,m l,f m,D n,F o,1 p,0 q,c r,G s,n t,N u,e v,B w,r x,U y,p z,A A,8 B,X C,S D,P E,T F,a G,M H,d I,K J,L K,3 L,C M,i N,9 O,E P,w Q,o R,z S,4 T,O U,q V,V W,J X,x Y,Z Z,u 0,l 1,y 2,W 3,s 4,Q 5,g 6,v 7,7 8,b 9,Y

Output example: There is no output.

I did expect it to print just fine the first string called "text" but it is not working. I tried even clearing out the buffer using getchar() but no results (this is what other websites said it would work). Can you explain what is wrong with my code?

>Solution :

Taking into account this code snippet

    lit_orig = alpha[0];
    lit_replace = alpha[2];

where there is used the index equal to 2 it seems that in the call of scanf

scanf("%s", alpha);

you are entering three characters. As a result the terminating zero character '\p' is written outside the array alpha in the memory occupied by the array text. As a result the array text contains an empty string.

You need to declare the array alpha at least like

char alpha[4] = {0}, 

And use the format string in the call of scanf the following way

scanf("%3s", alpha);

Leave a Reply