Lisanne Lisanne - 18 days ago 5
C Question

Read a string of 7 characters in C

I have:

char M[20] = "abcdabcdabcdabcd";

I can either print it as a string or as characters:

printf("%s\n", M); //print as string

for(i = 0;str[i] != '\0';i++) //print as characters

I want to read a string of 7 characters and store it in M such that afterwards when I print it as a string and as characters I get (assuming the 7 characters entered are: ABCDEFG):

ABCDEFG //output of printf("%s\n", M); when printed as string
ABCDEFG abcdabcd //output of the for loop above

My answer is:

for(K = 0;K<7;K++)
scanf(" %1c", &M[K]);

but the above doesn't work as it should.


it outputs


for both cases.


You should add a statement:M[7] = '\0'. The last character for the string should be '\0'.