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
{
printf("%c",str[i]);
}
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.
EDIT:
it outputs
ABCDEFGdabcdabcd
for both cases.
You should add a statement: M[7] = '\\0'
. The last character for the string should be '\\0'.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.