希望该程序输出“ Digi”,但为什么输出“ Dig)tal Bangladesh”。
有人可以解释吗?
#include<stdio.h>
int main(){
char str[120]="Digital Bangladesh";
int n;
n=strlen(str);
printf("%d \n",n);
str[4]="\0";
printf("%s",str);
return 0;
}
答案 0 :(得分:2)
我已经在注释中给出了基本的解释,并对代码进行了一些改进(将"\0"
替换为'\0'
,并将string.h
替换为strlen()
)。
#include <stdio.h>
#include <string.h>
int main() {
char str[120] = "Digital Bangladesh";
int n = strlen(str); // can combine declaration and assignment into a single statement;
// this will assign the actual length of string str to n
printf("%d \n", n);
str[4] = '\0'; // shouldn't be "\0" since anything in double quotes will be a string and not a character
// you are assigning 5th character (4th index + 1) of str to NULL ('\0') terminator character;
// now str will have content "Digi"
printf("%s", str);
return 0;
}